当用户输入“退出”时退出无限while循环(python),但如果用户输入数字,则将其与50进行比较

时间:2018-10-17 15:21:05

标签: python while-loop control-flow

我需要有关此问题的帮助。要求用户在无限while循环内输入一个数字,将这个数字进行比较,以使其等于50(小于,大于或等于)。但是要退出while循环,用户必须输入“退出”。我有下面的代码根据要求工作,但我想在最后写“ exit”(如果)语句。这样做肯定会导致错误。请随意选择其他方式。

while True:
x = input('please enter a number to compare or enter "exit" to exit the loop \n')
if x == "exit":
    exit()
elif int(x) > 50:
    print(x, 'is greater than 50')
elif int(x) < 50:
    print(x, 'is less than 50')
else:
    print('the number you entered is 50')

2 个答案:

答案 0 :(得分:0)

这是因为您试图解析字符串为int的“ exit” 您可以使用try和except。

答案 1 :(得分:0)

好吧,如果用户键入fkljhae会怎样?引发ValueError。还有...等等!对于任何非int输入,都会提高该值-"exit"满足此条件。

from sys import exit

while True:
    x = input('please enter a number to compare or enter "exit" to exit the loop \n')
    try:
        if int(x) > 50:
            print(x, 'is greater than 50')
        elif int(x) < 50:
            print(x, 'is less than 50')
        else:
            print('the number you entered is 50')
    except ValueError:
        if x == "exit":
            exit()

这不是特别好;如果print引发ValueError怎么办?让我们对其进行重构,以使int(x) try:块中只有except:

from sys import exit

while True:
    text = input('please enter a number to compare or enter "exit" to exit the loop \n')
    try:
        x = int(text)
    except ValueError:
        if text == "exit":
            exit()
    else:
        if x > 50:
            print(x, 'is greater than 50')
        elif x < 50:
            print(x, 'is less than 50')
        else:
            print('the number you entered is 50')

这更好,尽管"exit"不再位于底部。