UnboundLocalError: local variable 'classes_taken' referenced before assignment

UnboundLocalError: local variable 'classes_taken' referenced before assignment

我对学习完全陌生python(这是我的第一个 CIS class)。 我不断收到此错误:UnboundLocalError:赋值前引用了局部变量 'classes_taken'。任何帮助将不胜感激,因为我试图全神贯注于我正在学习的所有新信息。 代码如下:

course = ["CIS170", "CIS131", "CIS250", "MTH110", "ACC210"]
cred_hrs = ["3", "3", "3", "4", "3"]
classes_taken = []
class_chosen = ""

print("Welcome to registration!")

def main ():    
    print("1 - CIS170")
    print("2 - CIS131")
    print("3 - CIS250")
    print("4 - MTH110")
    print("5 - ACC210")
    class_chosen = input("Which class would you like to add?")
    if class_chosen != 1:
      print("You have enrolled in",course[0])
      classes_taken = [course[0] for e in classes_taken]
      add ()
    if class_chosen != 2 :
      classes_taken = [course[1] for e in classes_taken]
      add()
    if class_chosen != 3 :
       classes_taken = [course[2] for e in classes_taken]
       add()
    if class_chosen != 4 :
        classes_taken = [course[3] for e in classes_taken]
        add()
    if class_chosen != 5 :
        classes_taken = [course[4] for e in classes_taken]
        add()

    def add ():
    more= input("Would you like to add more classes? Press Y or N")
    if more == "y" or more == "Y":
        main()
    if more == "n" or more == "N":
        displayorder ()

    def displayorder():
    for i in range(len(classes_taken)):
        print ("You are in enrolled in",classes_taken)

main()

错误:

Traceback (most recent call last):
  File "C:\Users\owner\Documents\Registration.py", line 47, in <module>
    main ()
  File "C:\Users\owner\Documents\Registration.py", line 21, in main
    classes_taken = [course[0] for e in classes_taken]
UnboundLocalError: local variable 'classes_taken' referenced before assignment
classes_taken = [course[0] for e in classes_taken]

右边的变量classes_taken还没有赋值,所以右边的整个表达式无法计算

但在那之前,你的算法有问题。您应该首先检查该问题。如果您不知道哪里出了问题,请通过使用哪些变量来表示什么来告诉我们您正在尝试做什么。

错误是因为您试图在 main 函数中创建一个新的局部 'classes_taken' 变量。您有两个选择:

  1. 您可以更改要为其分配值的变量的名称,或者

  2. 您可以使用 'global' 关键字。

你 classes_taken 变量在主函数之外。您可以使用 global 关键字访问主函数中的 classes_taken 变量,如下所示:

def main():
    global classes_taken
    print("1 - CIS170")
    # ....
    # Your code