简体   繁体   中英

How can I make a program determine whether or not the input is an int in python?

Good afternoon. I am trying to create a program to print descriptions of numbers. I'm in very basic python and am a bit stuck on this particular problem. Can anyone tell me how to have the program distinguish between numbers to continue the program, and the Q, Bye or carriage return to end the statement?

while True:

    N = eval(input("Enter an input: number to continue, Q, bye or carriage return to quit")

    if N == int

        N => 0 print("positive")

        else print("negative")

You can use isinstance :

if isinstance(N,int):
    #do something

Note that this sort of thing isn't recommended. Especially when you're eval ing raw_input . Here I would try something like:

#python2
try:
   N = int(raw_input("Enter integer:"))
except ValueError:
   print "Not an integer!"

or on python3:

#python2
try:
   N = int(input("Enter integer:"))
except ValueError:
   print("Not an integer!")

I use a couple of different ways, depending on context:

try:
    i = int(a)
except ValueError:
    print >>sys.stderr, "Cannot be converted to integer"

or

if type(a) == type(1):
    print "Yep, that's an int"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM