我用了:
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)
但它总是即使它是一个整数说它是错的.
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)