python - 错误处理循环未按预期运行
问题描述
对编程非常陌生,我正在尝试编写一个待办事项列表程序,而不参考任何书籍或视频等。只是想自己弄清楚所有逻辑。我真的很困惑为什么这个函数的行为不像我期望的那样:
def edit_todo(todos):
show_todos(todos)
invalid_input = True
while invalid_input:
edit_selection = int(input("Select which to-do to edit: "))
try:
if edit_selection > len(todos) or edit_selection < 1:
print("That number is out of range. Please try again.")
except ValueError:
print("You must enter a valid selection. Please try again.")
todos[edit_selection-1] = str(input("Enter the new to-do text: "))
show_todos(todos)
调用此函数时,我想确保用户输入的数字与待办事项列表(待办事项)中的现有待办事项相对应。错误处理似乎适用于索引范围,但如果我输入说字母“m”,那么它只会继续并在此函数之外执行主程序循环,而不是激活 ValueError 异常并提示用户输入有效输入。
我一直盯着并试图重新安排和重新配置这个功能,但没有运气。我没看到什么?谢谢你的帮助!
更新:
感谢您所有的帮助!!!以下版本似乎按预期工作!
def edit_todo(todos):
show_todos(todos)
invalid_input = True
while invalid_input:
try:
edit_selection = int(input("Select which to-do to edit: "))
if edit_selection > len(todos) or edit_selection < 1:
raise IndexError
except ValueError:
print("You must enter a valid to-do number. Please try again.")
except IndexError:
print("That number does not correspond to a to-do in the list. Please try again.")
else:
invalid_input = False
todos[edit_selection-1] = str(input("Enter the new to-do text: "))
show_todos(todos)
解决方案
推荐阅读
- angular - 列表顺序更改角度 7
- c# - c# 返回客户名称字符串
- php - 如何显示选中的复选框和未选中的复选框
- alloy - Alloy5 中的默认运行命令:Alloy4 中的等价物是什么?
- python - 如何制作闪烁的文本选项
- regex - 无法将此正则表达式存储在变量中
- sql-server - sql server 分区性能
- jupyter-notebook - 错误 conda.core.link:_execute(700):安装包“conda-forge::jupyter_nbextensions_configurator-0.4.1-py37_0”时出错
- angular - 如何以角度限制最终用户对 URL 的更改
- python - 如何在我的自动点击器中添加左右鼠标按钮之间的切换?