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

Exit infinite while loop (python) when user enters "exit", but if users enters a number compare it to 50

我需要帮助解决这个问题。要求用户在无限 while 循环中输入一个数字,将这个数字与 50(小于、大于或等于)进行比较。但是为了退出这个 while 循环,用户必须输入 "exit"。我有以下根据要求工作的代码,但我希望 'exit' (if) 语句写在最后。这样做肯定会导致错误。请随时使用其他方式。

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')

这是因为你正在尝试解析 "exit" 这是字符串到 int 您可以使用 try 和 except.

嗯,如果用户键入 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" 不再位于底部,但更好。