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

ben*_*i79 3 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:
Run Code Online (Sandbox Code Playgroud)

但它总是即使它是一个整数说它是错的.

Jor*_*ley 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
Run Code Online (Sandbox Code Playgroud)

我喜欢这个并进一步抽象它

 def force_type(type_class,prompt,error_msg):
     while True:
         try:
            return type_class(prompt)
         except (ValueError,TypeError):
            print error_msg
Run Code Online (Sandbox Code Playgroud)

然后就变成了

 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)
 ...
Run Code Online (Sandbox Code Playgroud)

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

  • 这不是OOP.你能让它更多吗? (4认同)
  • @MorganThrapp肯定`def get_int(self,p,err_msg):`:P (2认同)