【问题标题】:I there any way to validate a number had been entered into an input?我有什么方法可以验证输入的数字是否已输入?
【发布时间】:2015-12-10 19:17:34
【问题描述】:
print("Now please enter a number")
No1 = int(input(">> "))

有什么方法可以验证用户是否使用 while 循环和变量输入了一个数字,例如:

NumberInput1 = False

print("Now please enter a number")
while NumberInput = False
    No1 = int(input(">> "))
    #if a number was entered
    NumberInput1 = True
    #if a number wasn't entered
    NumberInput1 = False
    print("That is not a number try again")

【问题讨论】:

标签: validation python-3.x input


【解决方案1】:

您可以使用try/except 来区分您的字符串是否可以转换为整数。

gotNumber = False
while not gotNumber:
    try:
        num = int(input('>> '))
        gotNumber = True
    except ValueError:
        print("That is not a number.")

【讨论】:

  • 酷。这里应该有一个按钮让你接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-14
相关资源
最近更新 更多