python - 虽然循环“继续”在尝试中不起作用,但最终除外
问题描述
尝试运行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
如果输入了除数字以外的任何内容,则需要继续循环,但循环到达finally
和break
s。
解决方案
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()
在循环底部添加了一个演示。
推荐阅读
- python - 如何调试本地进程调用的python?
- ruby-on-rails - TypeError(没有将字符串隐式转换为整数):Rails 6
- flask - 未调用 eventsource.onmessage - 烧瓶应用程序
- sql - 不使用游标执行查询
- reactjs - IdentityServer4 中 id_token 的受众错误
- android - 解码器初始化失败:OMX.qcom.video.decoder.avc,
- sharepoint - SPFx:在清单 JSON 中加载架构时出现问题
- python - 行中的唯一值到具有条件的列标题
- javascript - React Native 平面列表
- ios - Tableview scrollToRow(at:at:animated) 导致 scrollViewDidScroll(_) 被多次调用