0

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!

Nathan
  • 73,987
  • 14
  • 40
  • 69
  • 4
    None of those `global` statements do anything. Get rid of them. –  Jan 18 '13 at 15:55
  • 3
    Note that globals are generally a bad idea - pass values into your functions and return values back - globals cause more problems than they solve. – Gareth Latty Jan 18 '13 at 15:59

2 Answers2

13

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

mgilson
  • 300,191
  • 65
  • 633
  • 696
6

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.

  • 2
    One slight issue with this one, *define* implies it's only when you make a new global variable, and this isn't true, it's *assignment* to a global that requires the `global` keyword. – Gareth Latty Jan 18 '13 at 15:58
  • Such a small mistake and I'm not even confident of it, but I'll believe you and have fixed it. Good catch :) –  Jan 18 '13 at 16:00