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

Python日志程序报错SyntaxError: expected ':',请求排查解决

日志程序语法错误修复方案

核心错误分析

  1. else语句语法错误:代码中else userfinished == "n"是错误写法,else不能附带条件判断,要匹配"n"的输入需改用elif userfinished == "n",else仅用于兜底所有未匹配的情况。
  2. 缩进错误:f = open(currentDate, "w")之后的代码块整体缩进异常,Python对缩进层级要求严格,这部分代码需和currentDate定义保持同一缩进层级。
  3. 缺失模块导入:代码用到datetime、time、sys三个模块但未导入,运行时会触发NameError。

修正后的完整代码

import datetime
import time
import sys

currentDate = datetime.today().strftime('%Y-%m-%d')

f = open(currentDate, "w")
print("Write what you want to add into your journal, and it'll be saved when you hit enter.")
f.write(input())
f.close()
print("Are you done? (press 'y' if you are)")
userfinished = input()
if userfinished == "y":
    print("Alright then.")
    time.sleep(1)
    print("You can now read the file you've created in your operating system's file explorer (in built reader coming soon).")
    time.sleep(1)
    print("Goodbye.")
    sys.exit()
elif userfinished == "n":
    print("Alright, keep on writing.")
    f = open(currentDate, "a")
    f.write(input())
    f.close()  # 补充关闭文件,避免资源泄漏
else:
    print("Invalid input, exiting.")
    sys.exit()

额外优化提示

  • 建议用with语句管理文件,自动完成关闭操作,避免资源泄漏:
    with open(currentDate, "w") as f:
        print("Write what you want to add into your journal, and it'll be saved when you hit enter.")
        f.write(input())
    
  • 处理用户输入时可统一转小写并去除首尾空格,避免大小写或空格导致的匹配失败:userfinished = input().strip().lower()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 04:22:11