gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 08:46:47 24 4
gpt4 key购买 nike

我对学习 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com