以下代码通常可以接受吗?以这种方式实现所需的解决方案可能会出现哪些问题?
while True:
Iq = input("What is your Iq? ")
if Iq.isdigit():
print(Iq)
break
else:
print("that is not a number")
使用
.isdigit()
验证数字输入的潜在问题是:
即使您确实想要限制用户输入正整数,您也可能希望负数/非整数输入与完全非数字输入(例如
abc
或空字符串)有不同的错误消息。
这是一个更强大的输入函数,它允许负数或非整数输入,并且还支持可选的值边界检查。
def input_int(prompt='', lo_value=None, hi_value=None):
while True:
# Have the user input a string.
entry = input(prompt)
# Try to parse the string as a number.
try:
value = int(entry)
except ValueError:
# If they entered a float, round it to an int.
try:
value = round(float(entry))
except ValueError:
print('That is not a number.')
continue
# Bounds check the value.
if (lo_value is not None) and (value < lo_value):
print(f'Value cannot be less than {lo_value}.')
elif (hi_value is not None) and (value > hi_value):
print(f'Value cannot be more than {hi_value}.')
else:
return value