Python global lists [closed]

房东的猫 提交于 2019-12-11 13:42:20

问题


I'm learning python, and am having a problem with global variables/lists. I'm writing a basic manual tower of hanoi program, here's the program currently:

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])

I've tried a few variations, but every time I got the error "NameError: global name 'pillar1' is not defined".

What would be the best way to handle a global list in this setting? I'd prefer to just use one source file, if possible. Thanks!


回答1:


It's because you've "declared" it as pilar1, not pillar1




回答2:


The problem you encounter is pilar not being the same as pillar. After you fix that, you will no longer need the global declarations:

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])

Only time you need to use global is if you assign a global variable in a non-global scope, such as function definition:

# 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)

However you shouldn't use globals too much, instead use function parameters to pass values around.



来源:https://stackoverflow.com/questions/14402557/python-global-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!