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

无法退出codeUpLoop循环问题及Python JSON代码优化咨询

问题修复与代码优化建议

一、退出循环的问题修复

你的代码中有两处逻辑错误导致codeUpLoop循环无法正常退出:

1. 课程不存在分支的条件判断错误

在课程未找到的分支里,你写的判断逻辑永远为真——无论输入什么值,add != 'Y'和add != 'y'中总有一个成立,导致不管输入什么都会触发退出。正确逻辑应该是输入不是Y/y时退出,修改为:

if add.lower() != 'y':
    codeUpLoop = False

或者用逻辑与实现:

if add != 'Y' and add != 'y':
    codeUpLoop = False

2. 课程更新后的循环退出补充

当输入C/c设置codeUpLoop=False后,内层循环会退出,但外层upLoop仍为True,会回到主菜单。如果需要直接退出整个程序,可在设置codeUpLoop=False的同时添加upLoop=False;另外要注意,更新课程代码后,需要把新代码加入传入的l列表、移除旧代码,否则后续操作会找不到新代码。

二、代码优化建议(重点文件管理)

你的代码存在大量重复读写文件的操作,不仅效率低,还容易引发数据不一致问题,以下是针对性优化方案:

1. 重构JSON存储结构

当前courseInfo是列表套单个键值对的字典,操作极不方便。建议改成单个字典存储课程信息:

{
    "courseInfo": {
        "FHSC1014": "MECHANICS",
        "FHCT1024": "PROGRAMMING CONCEPT AND DESIGN"
    }
}

这种结构下,查找、修改、删除课程只需操作字典键值对,无需遍历列表,代码会简洁很多。

2. 减少文件IO操作

遵循一次性读取→内存中修改→一次性写入的流程,避免频繁打开关闭文件:

  • 读取:仅在需要刷新数据时一次性读取JSON文件到内存字典
  • 修改:所有操作在内存字典中完成,不涉及文件
  • 写入:修改完成后,一次性把内存字典写入文件覆盖原内容

示例工具函数:

def load_courses():
    try:
        with open("dict.json", 'r') as f:
            data = json.load(f)
            return data.get("courseInfo", {})
    except (FileNotFoundError, json.JSONDecodeError):
        print("课程文件不存在或格式错误,将创建新文件")
        return {}

def save_courses(courses):
    try:
        with open("dict.json", 'w') as f:
            json.dump({"courseInfo": courses}, f, indent=4)
        return True
    except Exception as e:
        print(f"保存失败: {str(e)}")
        return False

3. 简化逻辑与变量管理

  • 移除global temp,改用局部变量存储课程名称
  • 统一将用户输入转成小写(或大写),减少重复的多条件判断
  • 减少嵌套循环,拆分复杂逻辑为独立函数,提升代码可读性

4. 添加异常处理

针对文件不存在、权限不足、JSON格式错误等情况添加异常捕获,避免程序直接崩溃。

优化后的完整示例代码

import json
import os

def clear_screen():
    # 跨平台清屏
    os.system('cls' if os.name == 'nt' else 'clear')

def load_courses():
    try:
        with open("dict.json", 'r') as f:
            data = json.load(f)
            return data.get("courseInfo", {})
    except (FileNotFoundError, json.JSONDecodeError):
        print("课程文件不存在或格式错误,将创建新文件")
        return {}

def save_courses(courses):
    try:
        with open("dict.json", 'w') as f:
            json.dump({"courseInfo": courses}, f, indent=4)
        return True
    except Exception as e:
        print(f"保存失败: {str(e)}")
        return False

def update_course():
    courses = load_courses()
    while True:
        clear_screen()
        print("\nEdit \t <1>Course code \t <2>Course Name \t\t <E>xit")
        update_option = input("Enter Instruction: ").strip().lower()
        
        if update_option == 'e':
            break
        elif update_option == '1':
            while True:
                code_to_edit = input("Enter Course Code to Edit: ").strip()
                if code_to_edit not in courses:
                    clear_screen()
                    print("Course Not Found\nEnter Y to add Course, or any key to quit")
                    add = input().strip().lower()
                    if add != 'y':
                        break
                    course_name = input("Enter Course Name: ").strip()
                    courses[code_to_edit] = course_name
                    if save_courses(courses):
                        print("Course added successfully!")
                    input("Press Enter to continue...")
                    break
                else:
                    new_code = input("Enter New Course Code: ").strip()
                    if new_code in courses:
                        print("Course already exists!")
                        input("Press Enter to continue...")
                        continue
                    course_name = courses.pop(code_to_edit)
                    courses[new_code] = course_name
                    if save_courses(courses):
                        clear_screen()
                        print("Course Updated Successfully\nPress Enter to continue or Enter C to quit")
                        code_up_op = input().strip().lower()
                        if code_up_op == 'c':
                            return
                        else:
                            break
                    else:
                        courses[code_to_edit] = course_name
                        input("Update failed, press Enter to continue...")
                        break
        elif update_option == '2':
            # 课程名称修改逻辑可参考上述结构实现
            pass
        else:
            print("Invalid option!")
            input("Press Enter to continue...")

if __name__ == "__main__":
    update_course()

内容的提问来源于stack exchange,提问作者Cheah Ken Win

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 23:27:23