如何“以其他方式从头开始运行该程序”?

时间:2019-10-08 14:04:50

标签: python python-3.x

如果用户输入的代码超出了代码范围,那么我要从头开始继续运行该程序。

number = input("Enter your number up to 100 : ")

while int(number) < 100:
     print(number)

else:
    print("\n**The number is outside the Limit.**")

3 个答案:

答案 0 :(得分:1)

您确定要在代码中使用“ while”吗?我不确定您需要什么,但可以考虑一下:

while True:
    number = input("Enter your number up to 100 : ")
    if int(number) < 100:
        print(number)
        break
    else:
        print("\n**The number is outside the Limit.**")

答案 1 :(得分:1)

这可能是最简单的:

while True:
    number = input("Enter your number up to 100 : ")
    if int(number) < 100:
        print(number)
        break
    print("\n**The number is outside the Limit.**")

但是,如果用户输入非数字值怎么办?当您尝试将字符串转换为int时,将引发异常。所以:

while True:
    number = input("Enter your number up to 100 : ")
    try:
        if int(number) < 100:
            print(number)
            break
        print("\n**The number is outside the Limit.**")
    except ValueError:
        print("You did not enter a number")

答案 2 :(得分:0)

我假设您要发出第一个提示,然后继续接受用户输入,除非超出限制,在这种情况下,请再次打印警告和第一个提示...

在这种情况下,您需要与第一个提示分开收集输入:

while True:
    print("Enter your number up to 100:")
    while True:
        number = int(input())
        if number < 100:
            print("number is:", number)
        else:
            print("number is outside the limit")
            break

示例输出:

Enter your number up to 100:
12
number is: 12
123
number is outside the limit
Enter your number up to 100:
12
number is: 12
3
number is: 3

当然,我可能无法正确解释您的问题,但是希望对您有所帮助。