首页 > 解决方案 > 虽然循环“继续”在尝试中不起作用,但最终除外

问题描述

尝试运行while循环直到输入有效:

while True:
    try:
        print('open')    
        num = int(input("Enter number:"))
        print(num)

    except ValueError:
        print('Error:"Please enter number only"') 
        continue #this continue is not working, the loop runs and break at finally

    finally:
        print('close')
        break

如果输入了除数字以外的任何内容,则需要继续循环,但循环到达finallybreaks。

标签: pythonpython-3.xwhile-looptry-exceptcontinue

解决方案


finally始终在 try-except 之后运行。你想要else只有在 try-block 没有引发异常时才会运行。

顺便说一句,尽量减少 try 块中的代码,以避免误报。

while True:
    inp = input("Enter number: ")
    try:
        num = int(inp)
    except ValueError:
        print('Error: Please enter number only')
        continue
    else:
        print(num)
        break
    print('This will never print')  # Added just for demo

测试运行:

Enter number: f
Error: Please enter number only
Enter number: 15
15

请注意,continue您的示例中实际上不需要,因此我print()在循环底部添加了一个演示。


推荐阅读