python - while 循环 "continue"在尝试内不起作用,除了,最后

标签 python python-3.x while-loop try-except continue

尝试运行 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

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

最佳答案

finally始终在 try- except 之后运行。您需要 else,它仅在 try block 不引发异常时运行

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

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

关于python - while 循环 "continue"在尝试内不起作用,除了,最后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68330528/

相关文章:

python - 如何为 Python 2 和 3 上传通用 Python Wheel?

python - 为什么在 Python 中完全使用 "dict()"?

java - 循环不执行内部if语句

ruby - while 循环和 Mechanize Ruby 的问题

python - 泛型类的类方法

python - 如何提取在 python 中渲染 HTML 页面期间获得的 url 列表?

python - Pygame 无响应显示

python - 如何将列表应用于 Pandas 组

python - 转换字典列表,根据键组合列表项

c++ - 在c中使用scanf停止无限while循环?