输入非整数值时,如何防止程序终止?

时间:2019-04-15 02:08:23

标签: python python-2.7 loops

如何使它在用户输入非整数值后循环运行?

我已经尝试使用“ while int(u)!= int”

u = raw_input("enter a positive number")
while u != int:
    u = raw_input("Please enter a number")
if u == int:
    print "that's a number"

2 个答案:

答案 0 :(得分:1)

尝试将其强制转换为类型,如果不是则捕获异常

while True:
    u = raw_input("Enter a positive number: ")
    try:
        num = int(u)
    except ValueError:
        print "{} is not a number".format(u)
        continue
    break
print "{} is a number".format(num)

这只会检查以确保它是整数,而不是正数,但这很容易添加。

答案 1 :(得分:0)

您忘记了.isdigit()

while True:
    u = raw_input("Enter a positive number: ")
    if not u.isdigit():
        print u, "is not a number"
        continue
    u = int(u)
print u, "is a number"

示例输出:

Enter a positive number: sf
sf is not a number
Enter a positive number: 1
1 is a number