You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编辑待办事项(TODO)应用时触发TypeError错误求助

解决待办事项编辑功能的TypeError错误

错误原因

在edit分支中,input()函数获取的用户输入默认是字符串类型,直接执行number - 1时,相当于尝试用字符串减去整数,Python不支持这种跨类型运算,因此触发TypeError:不支持对'str'和'int'执行减法运算。对比complete分支的代码,你已经正确将输入转为整数类型,但edit分支漏掉了这一步。

修复后的代码

todos = []

while True:
    user_action = input("Type Add, Show, Edit, Complete or exit: ")
    user_action = user_action.strip()
    match user_action:
        case 'add':
            todo = input("Enter a To-D0: ")
            todO = todo.capitalize()
            todos.append(todO)
        case 'show':
            for index, item in enumerate(todos):
                row = f"{index + 1 }:-{item}"
                print(row)

        case 'edit':
            # 将输入转为整数类型,解决类型不匹配问题
            number = int(input("Number of To-Do to Edit:"))
            number = number - 1
            new_todo = input("Enter new To_Do: ")
            todos[number] = new_todo
        case 'complete':
            number = int(input("Value you want to Complete:"))
            todos.pop(number - 1)
        case 'exit':
            break 
print("Bye")

额外优化建议(可选)

如果要避免用户输入非数字内容时触发ValueError,可以添加输入验证逻辑:

case 'edit':
    while True:
        try:
            number = int(input("Number of To-Do to Edit:"))
            break
        except ValueError:
            print("请输入有效的数字!")
    number = number - 1
    new_todo = input("Enter new To_Do: ")
    todos[number] = new_todo

内容的提问来源于stack exchange,提问作者Muddassar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:07:03