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

Python if分支调用函数报错及课程查询功能异常问题求助

问题修复方案

核心问题说明

现有代码的两个问题根源如下:

  • 执行顺序错误:Python代码从上到下逐行执行,你将getCourses、getDescription函数定义、课程数据加载逻辑都放在了主循环之后,主循环运行时这些函数还未被定义,调用自然会报错;同时V分支直接break跳出循环后才会执行后面的打印课程、查询逻辑,导致V功能只能靠跳出循环触发,还会无预期弹出课程输入要求。
  • 逻辑错位:V对应的课程列表打印、L对应的课程代码查询逻辑都放在了主循环外部,没有绑定到对应的操作分支中。

现有结构完全可以实现预期功能,只需要调整代码顺序和分支逻辑即可。

修复后完整代码

def getCourses():
    courses = {}
    with open("assignments/assignment-19/courses.txt") as file:
        for line in file:
            data = line.split(':')
            code = data[0].strip()
            className = data[1].strip()
            courses[code] = className
        return courses

def getDescription(courseList):
    code = input("Enter course code: ").strip().lower()
    if code in courseList:
        print(f"{courseList[code]}")
    else:
        print(f"Sorry {code} is not in our system")

# 预加载课程数据,避免每次操作重复读取文件
courseList = getCourses()

while True:
    command = input("(V)iew, (L)ookup, or (Q)uit: ").lower()
    if command == "v":
        # 打印全部课程
        for code, name in courseList.items():
            print(f"{code}: {name}")
    elif command == "l":
        # 调用课程查询功能
        getDescription(courseList)
    elif command == "q":
        print("Goodbye!")
        break
    else:
        print("Invalid command")

如果你的本地courses.txt路径和代码中填写的一致,直接运行即可实现预期功能,兼容V/L/Q的大小写输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:36:01