首页 > 解决方案 > 错误处理循环未按预期运行

问题描述

对编程非常陌生,我正在尝试编写一个待办事项列表程序,而不参考任何书籍或视频等。只是想自己弄清楚所有逻辑。我真的很困惑为什么这个函数的行为不像我期望的那样:

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)

标签: pythonexceptionvalueerror

解决方案


推荐阅读