打印出我想显示的数据时出现问题

我正在修改我正在编写的一个程序,这样它就不会继续运行,除非他们输入的输入与存储在列表中的单词相匹配。但是在我这样做之后,它不会让我打印出我拥有的数据,这是代码


while True:



        dept = input('what department are you  in right now: ')

        dept = dept.upper()

        if dept not in department_storage:

            print("not approriate response")

            continue

        else:

            break

        if dept in department_storage:

            department_url = requests.get(f"https://api.umd.io/v0/courses?dept_id={dept}")

            specific_major =department_url.json()

            keep_keys = ["course_id"]

            courses = [{k: json_dict[k] for k in keep_keys}

                      for json_dict in specific_major]



        #return courses,dept

            print(courses)



我试图打印出课程变量,但是当我尝试运行该函数时它不显示打印输出,并且在我运行它时它不显示任何错误所以我迷失了我做错了什么以及如何修复它 。我想知道我是否可以向友好的堆栈溢出社区寻求帮助。


慕仙森
浏览 80回答 2
2回答

收到一只叮咚

由于多种原因,您可能无法获得输出:-你有输入吗?解释器可能正在等待尚未输入的用户输入。如果它是真的,也许它dept not in department_storage正在打破循环。break让你脱离循环。courses是一个空对象,可能是因为你得到的结果有空对象。您可以import pdb; pdb.set_trace();在代码中的不同位置添加,并在调试器中写入变量名称以查看值。这将有助于您进行调查。根据要求,我的建议是以下代码:-while True:    dept = input('what department are you in right now: (type exit to quit)')    dept = dept.upper()    if dept == 'EXIT':        break    if dept not in department_storage:        print("this department does not exist, enter correct department")    else:        try:            department_url = requests.get(f"https://api.umd.io/v0/courses?dept_id={dept}")            specific_major =department_url.json()            keep_keys = ["course_id"]            courses = [{k: json_dict[k] for k in keep_keys}                      for json_dict in specific_major]            print(courses)        except Exception as e:            print(e)

慕容森

break命令强制退出 while 循环并停止接受输入。尝试:if dept in department_storage:    ...# if dept not in department_storageelse:    ...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python