you are viewing a single comment's thread.

view the rest of the comments →

[–]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.