Global Variables

Greetings everyone.

For Study Drill 36 (LPTHW), I decided to make a linear RPG instead of another choose your own adventure game. Anyway, just about all the variables are lists or dicts except for one int type variable that keeps track of player gold.

I declared everything outside of the functions to make them global. One of the functions is to update player gold when the player buys or sells items. When I ran the program I would get an error about using an unassigned local variable. I Googled the error and found out I need to use the keyword global for player gold.

I understand the reasoning here. But I was wondering how come I can manipulating the dicts and lists I have in each of my functions without having to use the global keyword?

Hey @papercut2k, I believe you want do this:

player_gold = 0

def someroom():
    global player_glod
    player_gold += 20

The global player_gold is the magic that lets your function modify that value.

Gotcha.

I was wondering why python lists and dicts do not require the global keyword to be able to use them in functions.

Well, that’s a little bit of a complicated topic, but basically you only need to get access to a dict, and then you are changing its contents, so you’re not reassigning it. If you do this:

player_gold = 30

You’re actually changing the value of player_gold, or more like pointing the name player_gold at a new number. This is why you need the global keyword otherwise Python thinks you’re making a new local variable for the function.

With a dict though you aren’t changing where the variable goes, you’re changing in side it:

names['frank'] = "Frankie"

You don’t change where names points or what it is, you’re just using it so that’s fine.

1 Like