python - 未绑定(bind)本地错误: local variable 'classes_taken' referenced before assignment

标签 python python-3.6 local-variables

我对学习 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”变量。您有两个选择:

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

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

您的classes_taken变量位于主函数之外。您可以使用 global 关键字来访问 main 函数内的classes_taken 变量,如下所示:

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

关于python - 未绑定(bind)本地错误: local variable 'classes_taken' referenced before assignment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53273893/

相关文章:

python - 如何将参数从 mock.patch 传递给 new_callable?

c - 栈中auto变量占用的内存空间是多少

python - 重新运行调试器时如何避免重新加载包

python - 使用 pandas df 的具有多个 if 的 lambda 函数

opencv - 无法访问网络摄像头 OpenCV 3.3 Python 3

python - 在 Raspbian 系统上安装适用于 Python 3.6 的 mysqlclient

python - 如何在 GUI 中嵌入外部窗口(Python + Glade + Gtk3)

python - 导入导入 GPL 库的库?

vba - 有一个在过程结束后仍然存在的局部变量

google-sheets - 我可以在 Google 电子表格公式中定义本地值(或变量)吗?