我正在尝试处理用户的错误输入,例如浮点数和长度低于4且高于4的整数,这样无论何时发生,我都要求用户重新输入4位数。
预期结果。
>>> beginning = input('Enter date: ')
>>> Enter date: 1985.0
>>> Please give a four digit integer for date.
>>> Enter date: 19.8
>>> Please give a four digit integer for date.
>>> Enter date: blabla
>>> Please give a four digit integer for date.
>>> Enter date: 200
>>> Please give a four digit integer for date.
>>> Enter date: 20000
>>> Please give a four digit integer for date.
>>> Enter date: 1980
>>> # This is good
这是我的尝试。
def reading_ans():
while True:
try:
ans = input('Enter date: ')
if float(ans) != float(int(float((ans)))):
print("Please give a four digit integer for date.")
elif len(ans) != 4:
print("Please give a four digit integer for date.")
else:
return ans
答案 0 :(得分:0)
如果ans.isdigit()
仅由数字组成,我建议您的条件使用True
仅ans
的事实。
def reading_ans():
while True:
ans = input('Enter date: ')
if len(ans) == 4 and ans.isdigit():
return ans
print("Please give a four digit integer for date.")