【问题标题】:How do you check if input is numerical in Python? [duplicate]如何检查 Python 中的输入是否为数字? [复制]
【发布时间】:2017-11-10 17:36:23
【问题描述】:

我已经用 Python 编写了一个脚本,我想编写它,所以当它询问“你的年龄是多少?”时,如果你不输入数字。它会说“请输入一个数字”,然后重复原来的问题。我尝试了许多在其他帖子上看到的不同建议,但没有一个有效。

这是脚本:

yesorno = "yes"

while yesorno == "yes" :
    import time
    Age = 0
    Age = int(input("What is your age?"))
    Age = Age*365*24
    print(Age)
    yesorno = input("Would you like to run again?(yes/no)")

while yesorno != "no" :    
print("Please input yes or no")
yesorno = input("Would you like to run again?(yes/no)")

while yesorno == "no" :
print("Program stopping...")
import sys
sys.exit("Program stopping...")

【问题讨论】:

  • 还有很多贴子教你如何循环直到输入有效。

标签: python


【解决方案1】:

有很多方法可以做到这一点,但请允许我推荐一种添加到您现有代码中的方法,重点关注这一行:

Age = int(input("What is your age?"))

您可能已经知道,如果该人输入的不是整数,则此行会引发错误。

您可以在 try...except... 块中捕获这些错误,但在该行中输入任何非 int 时引发的错误除外。

try:
    Age = int(input("What is your age?"))
except ValueError:
    print("Please input a number")

为了让这个循环继续,我将yesorno放在try语句中,这样它只在年龄输入成功时执行,否则,就像用户输入yes一样做出反应,如下所示:

 try:
    Age = int(input("What is your age?"))
    Age = Age*365*24
    print(Age)
    yesorno = input("Would you like to run again?(yes/no)")
except ValueError:
    print("Please input a number")
    yesorno = "yes"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-19
    • 2013-12-04
    • 2013-11-24
    • 2015-08-17
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    • 2011-05-10
    相关资源
    最近更新 更多