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

Python Crash Course第10章remember_me代码无法正常运行求助

问题分析与修复:《Python Crash Course(第3版)》remember_me示例异常问题

问题根源

你的代码在username.json文件存在但为空时无法触发输入提示,核心原因有两点:

  • 当文件存在但内容为空时,get_stored_username会执行json.loads(""),这会直接抛出JSONDecodeError,导致程序崩溃,无法进入greet_user的else分支。
  • get_new_username函数中重复定义path变量,属于冗余代码,破坏了参数传递的一致性。

修复后的代码

from pathlib import Path
import json


def get_stored_username(path):
    if path.exists():
        try:
            contents = path.read_text().strip()  # 去除首尾空白字符
            if not contents:  # 处理空内容场景
                return None
            username = json.loads(contents)
            return username
        except json.JSONDecodeError:  # 捕获JSON解析异常
            return None
    return None

def get_new_username(path):
    username = input("What is your username? > ")
    contents = json.dumps(username)
    path.write_text(contents)
    return username

def greet_user():
    path = Path("username.json")
    username = get_stored_username(path)
    if username:
        print(f"Welcome back, {username.title()}!")
    else:
        username = get_new_username(path)
        print(f"We'll remember you when you get back, {username.title()}!")
    
greet_user()

关键修复点

  • 在get_stored_username中添加try-except块捕获JSONDecodeError,确保文件内容无效时返回None,让程序能正常进入else分支触发输入提示。
  • 增加空内容判断(if not contents),覆盖文件存在但全是空白字符的场景。
  • 删除get_new_username中重复定义的path变量,直接使用传入的参数,保持代码逻辑一致性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:42:09