如何检查Python中的整数输入?

时间:2015-11-12 20:19:47

标签: python input

我用过:

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:

但即使它是一个整数,也总是说错了。

3 个答案:

答案 0 :(得分:9)

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

我喜欢这个并进一步抽象

 def force_type(type_class,prompt,error_msg):
     while True:
         try:
            return type_class(prompt)
         except (ValueError,TypeError):
            print error_msg
然后它就变成了

 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)
 ...

如果你想要进行类型检查,你应该〜〜使用type(var)你应该使用isinstance(var,int)

答案 1 :(得分:1)

要检查类型,您可以这样做:

type(aVar) is aType

无论如何,正如凯文在评论中所说,你已经将输入包装到int中,所以它实际上是一个int或你的程序崩溃了

答案 2 :(得分:0)

尝试

if type(day) == int and type(month) == int and type(year) == int