如果用户输入 "done",我如何打破 while 循环并转到 finally 块

How can I break the while loop and go to the finally block if the user entered "done"

largest = None
smallest = None
l = []
while True:
    try:
        num = input("Enter a number: ")
    except NameError as err:
        if err == "done":
            break
        else:
            print("Invalid input")
    finally:
        l.append(num)
        l.sort()
        largest = l[-1]
        smallest = l[0]


print("Maximum", largest)
print("Minimim", smallest)

重构逻辑。 NameError 不会发生并且 finally 不需要...只需在 "finally" 完成后将其放在 while 之外。

nums = []

while True:
    num = input('Enter a number or "done": ')  # num is a string at this point
    if num == 'done':
        break
    try:
        # try to convert num to integer...
        num = int(num)  # This can fail with ValueError, so is in try
        nums.append(num)   # This won't run if above raises exception
    except ValueError:
        print("Invalid input")

# No need to sort...
print("Maximum", max(nums)) 
print("Minimum", min(nums))

此代码看起来像是 Python 2.x,其中 input() 尝试评估输入,如果您键入的字符串不是变量名称,则会发出错误信号。 Python 3.x 在您键入 done 时不会发出错误信号。

所以只是比较输入。稍后您可以在尝试将其转换为 int.

时进行错误检查
while True:
    num = input("Enter a number")
    if num == "done":
        break
    try:
        num = int(num)
    except ValueError:
        print("Invalid input")
        continue
    l.append(num)
l.sort()
largest = l[-1]
smallest = l[0]