检查输入是否为整数

Shu*_*dia 2 python integer

我不知道如何使用isinstance,但这是我尝试过的:

age = int(input("Enter your Age: "))
if isinstance(age,int):
    continue
else:
    print ("Not an integer")
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?这也会使我的程序终止吗?或者让我重新输入我的年龄?

如果输入不是整数,我希望它不断要求我重新输入。

Tim*_*ker 6

如果用户输入的不是整数,这将不起作用,因为调用int()将触发ValueError. 如果int()确实成功,则无需再检查isinstance()。此外,continue仅在fororwhile循环中才有意义。相反,请执行以下操作:

while True:      # keep looping until we break out of the loop
    try:
        age = int(input("Enter your age: "))
        break    # exit the loop if the previous line succeeded
    except ValueError:
        print("Please enter an integer!")
# If program execution makes it here, we know that "age" contains an integer
Run Code Online (Sandbox Code Playgroud)