我正在尝试制作一个可以在班级中添加/删除/显示学生的程序,这5个班级是列表中的5个列表。
非常感谢您的帮助。
当我运行此代码时:
global classes
def intro():
print("Welcome to Powerschool v2.0!")
print("Actions:")
print("1. Add Student")
print("2. Delete Student")
print("3. Show Students in a Class")
print("4. Show All Students")
x = int(input())
while x<1 or x>4:
print ("Please choose an action, 1-4.")
x = int(input())
if x == 1:
action1()
elif x == 2:
action2()
elif x == 3:
action3()
elif x == 4:
action4()
classes = [[],[],[],[],[]]
return classes
def action1():
print("Which Class? 1-5")
a = int(input())
print("Please enter the student's name.")
z = input()
classes[a-1].append(z)
again()
def action2():
print ("Which Class? 1-5")
print ("Which student?")
again()
def action3():
print ("Which Class? 1-5")
y = int(input())
if y == 1:
print (classes[0])
elif y == 2:
print (classes[1])
elif y == 3:
print (classes[2])
elif y == 4:
print (classes[3])
elif y == 5:
print (classes[4])
again()
def action4():
print (classes)
again()
def again():
print("Would you like to do something else? y/n")
h = input()
if h == "y":
intro()
else:
quit
def main():
intro()
main()
我的错误是:
Traceback (most recent call last):
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 67, in <module>
main()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 65, in main
intro()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 19, in intro
action1()
File "C:\Documents and Settings\user1\My Documents\Downloads\az_studenttracker.py", line 33, in action1
classes[a-1].append(z)
NameError: name 'classes' is not defined
我在intro()末尾做了
return classes
,但是我发现那是行不通的。我遵循了一些建议,但没有真正发生任何事情:/
最佳答案
这是因为classes
超出了后两种方法的范围。因此,您有两个选择:
选项1
将类传递给方法action1(), action2(), etc
,如下所示:def action1(classes)
...以及何时调用:action1(classes) //with the classes var you just made
选项2(推荐)
只需将classes
var放在您的方法外,或将其声明为global
,如下所示:global classes = [[],[],[],[],[]]
...就在之前:def intro()
通常,您应该阅读有关退货的工作方式的信息。您编写的代码中没有必要
关于python - Python:返回列表不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26950574/