简体   繁体   中英

How do I check an input for an integer in Python?

I used:

day = int(input('Please input the day you were born: e.g 8th=8 21st = 21 : '))
month = int(input('Please input the month you were born: e.g may = 5 december = 12 : '))
year = int(input('Please input the year you were born: e.g 2001 / 1961 : '))

if day == int and month == int and year == int:

But it always even when it's an integer says it's wrong.

def get_int(p,error_msg="Thats Not An Int!"):
    while True:
         try:
            return int(raw_input(p))
         except (ValueError,TypeError):
            print "ERROR: %s"%error_msg

day = get_int('Please input the day you were born: e.g 8th=8 21st = 21 : ')
#day is guaranteed to be an int

I like to take this and abstract it further

 def force_type(type_class,prompt,error_msg):
     while True:
         try:
            return type_class(prompt)
         except (ValueError,TypeError):
            print error_msg

then it simply becomes

 def get_int(p,err_msg):
     return force_type(int,p,err_msg)
 def get_float(p,err_msg):
     return force_type(float,p,err_msg)
 ...

allthat said if you want to typecheck you should ~ not ~ use type(var) you should use isinstance(var,int)

To check type you can do:

type(aVar) is aType

Anyway, as Kevin said in a comment you're already wrapping input to int, so either it's actually an int or your program crashed

尝试

if type(day) == int and type(month) == int and type(year) == 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