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

Python Todo应用将if替换为elif后报错,寻求解决方法

解决Todo应用中if转elif后的语法错误

核心语法错误原因

你替换后出现的「Statement expected, found Py:ELIF_KEYWORD」等错误,根源是**elif必须直接紧跟在if或前一个elif代码块之后,不能被无关语句打断**。

看你替换后的代码:在elif "completed"代码块结束后,插入了一行print("That task has been completed, congratulation!"),这行代码直接打破了if-elif的连续判断结构,导致后面的elif "show"找不到对应的起始if,触发语法错误。

同时原代码还有几个逻辑问题:

  • 那行完成提示不管用户有没有执行completed操作都会打印,逻辑错误
  • edit操作的文件写入代码缩进错误,不管有没有执行edit都会触发写入
  • 用list作为变量名会覆盖Python内置类型,不规范

修正后的代码

prompt = " Add or show  or type exit to quit the program  or edit to edit a item in your list  : "
todo_list = []  # 替换内置list作为变量名,避免冲突

while True:
    useraction = input(prompt + " you can also write completed to remove a task that you have done ")
    useraction = useraction.strip()
    
    if "add" in useraction:
        todo = useraction[4:]
        with open("app.txt", "r") as file:
            todo_list = file.readlines()

        todo_list.append(todo + "\n")  # 补充换行符,避免写入后内容粘连
        with open("app.txt", "w") as file:
            file.writelines(todo_list)

    elif "completed" in useraction:
        num = int(input("Please write the number of the task that is completed: "))
        with open("app.txt", "r") as file:
            todo_list = file.readlines()
        todo_list.pop(num - 1)
        # 仅在完成操作后打印提示,并写入文件
        print("That task has been completed, congratulations!")
        with open("app.txt", "w") as file:
            file.writelines(todo_list)

    elif "show" in useraction:
        with open("app.txt", "r") as file:
            todo_list = file.readlines()

        for index, item in enumerate(todo_list):
            item = item.strip("\n")
            row = f"{index + 1}-{item}"
            row = row.title()
            print(row)

    elif "exit" in useraction:
        break

    elif "edit" in useraction:
        number = int(input("please write the number of the item that you want to modify : "))
        number = number - 1

        with open("app.txt", "r") as file:
            todo_list = file.readlines()
        new_todo = input("please write the new thing that you want to do : ")
        todo_list[number] = new_todo + "\n"  # 补充换行符
        with open("app.txt", "w") as file:
            file.writelines(todo_list)

print("Bye !")

关键修正点说明

  1. 修复if-elif结构:把所有操作的判断放到连续的if-elif链中,中间不插入无关语句,确保每个elif都有对应的前置判断
  2. 调整提示打印逻辑:仅在执行completed操作后打印完成提示,避免无效输出
  3. 修正文件写入位置:将completed和edit的文件写入逻辑放到对应代码块内,避免无关操作触发写入
  4. 变量名规范:用todo_list代替list,避免覆盖Python内置类型
  5. 补充换行符:给新增/修改的todo添加\n,确保文件中每个任务单独一行,读取时格式正常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:52:52