我用过:
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:
但即使它是一个整数,它也总是说它是错误的。
最佳答案
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)
关于python - 如何检查 Python 中的整数输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33680570/