通过isdigit()方法强制整数输入
下面这段代码的写法在一般情况下可以接受吗?如果用这种方式来实现所需的解决方案,可能会出现哪些问题呢?
while True:
Iq = input("What is your Iq? ")
if Iq.isdigit():
print(Iq)
break
else:
print("that is not a number")
1 个回答
0
使用 .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