使用 isdigit() 方法强制输入整数

问题描述 投票:0回答:1

以下代码通常可以接受吗?以这种方式实现所需的解决方案可能会出现哪些问题?

while True:
    Iq = input("What is your Iq? ")
    if Iq.isdigit():
        print(Iq)
        break
    else:
        print("that is not a number")
python python-3.x conventions
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
© www.soinside.com 2019 - 2024. All rights reserved.