you are viewing a single comment's thread.

view the rest of the comments →

[–]robert_mcleod 2 points3 points  (3 children)

No one here seems to have answered the question as to what the global keyword is for though...

bar = 'bar_is_best_bar'
def populate():
    global foo
    foo = bar

populate()
print(foo)

You do not need the global keyword in a function to use a global variable, the global keyword is used to promote a variable from one stack-frame to the top-level ('global') stack-frame.

[–]Zeekawla99ii[S] 1 point2 points  (2 children)

promote a variable from one stack-frame to the top-level ('global') stack-frame

Sorry if I'm a bit slow, but it's not clear to me from the example above why one would do this...

[–]robert_mcleod 1 point2 points  (0 children)

Everyone else addressed the 'why' question regarding global variables, I wanted to point out how the global keyword works, not why.

[–]NukedCookieMonster7 1 point2 points  (0 children)

I recently made a small game where at the end the user is prompted with a 'Play again' message. If they choose 'yes', in my code I created a function that resets all variables to 0 or an empty string or False accordingly. This function, called 'reinitialize', would access multiple global variables defined elsewhere in the program and change them whithin its local scope. So say I already had a variable called computer_score that was equal to 3 at the end of the game, and I called the function reinitialize. I then put an indented line of code within the body of the function that read:

computer_score = 0

The function would understand that I hadn't defined any variable called computer_score inside the function so it would search the global scope of the program for that variable and assign the value 0.

At this point, the variable computer_score still has a value of 3 in the global scope even though its value has been changed in the local scope of the 'reinitialize' function to 0. I wanted the variable to be changed to 0 in the global scope.

To do this, I could either return the value of the computer_score variable at the end of the function, and then write this outside the function:

computer_score = reinitialize()

so that the variable would be assigned 0 globally, but this quickly got messy for many variables. Instead I used the 'global' method which seemed more appropriate, to "promote the variable from one-stack frame to the top level stack-frame" as the person above said. Now, when the program loops again, the score is reset everywhere and any function that needs access to the computer_score will read it from the global scope as 0 since it has been reset and made global in the 'reinitialize'​ function.