我正在学习python,并且遇到了全局变量/列表的问题。我正在编写河内计划的基本手册,这是目前的程序:
pilar1 = [5,4,3,2,1,0]
pilar2 = [0,0,0,0,0,0]
pilar3 = [0,0,0,0,0,0]
def tower_of_hanoi():
global pillar1
global pillar2
global pillar3
print_info()
def print_info():
global pillar1
global pillar2
global pillar3
for i in range(4,-1,-1):
print(pillar1[i], " ", pillar2[i], " ", pillar3[i])
我尝试了一些变体,但每次我收到错误" NameError:全局名称' pillar1'未定义"。
在此设置中处理全局列表的最佳方法是什么?如果可能的话,我更愿意只使用一个源文件。谢谢!
答案 0 :(得分:10)
这是因为您已将其“声明”为pilar1
,而不是pillar1
答案 1 :(得分:6)
您遇到的问题是pilar
与pillar
不同。
解决之后,您将不再需要global
声明:
pilar1 = [5,4,3,2,1,0]
pilar2 = [0,0,0,0,0,0]
pilar3 = [0,0,0,0,0,0]
def tower_of_hanoi():
print_info()
def print_info():
for i in range(4,-1,-1):
print(pillar1[i], " ", pillar2[i], " ", pillar3[i])
只有在非全局范围内分配全局变量时才需要使用全局变量,例如函数定义:
# global variable, can be used anywhere within the file since it's
# declared in the global scope
my_int = 5
def init_list():
# global variable, can be used anywhere within the file after
# init_list gets called, since it's declared with "global" keyword
global my_list
my_list = [1, 2, 3]
def my_function():
# local variable, can be used only within my_function's scope
my_str = "hello"
# init's global "my_list" variable here, which can then be used anywhere
init_list()
my_list.append(5)
my_function()
print(my_list)
但是你不应该使用全局变量,而是使用函数参数来传递值。