Skip to main content
gamedev.net
🔒 Locked

Globals in Python

Started by FlaiseSaffron 4 replies 2.1k views
Original Post
FlaiseSaffron
FlaiseSaffron
I am having trouble modifying a variable from inside a function defined at the same scope:

minutes_left = 60 * 24 * 7

...

def crossroads():
    ...
    minutes_left = minutes_left - 1  # error



I get the error: local variable 'minutes_left' referenced before assignment Please help me out, because online tutorials are not.
Alpha_ProgDes
Alpha_ProgDes
I'm confused:
Quote:
Python says:
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

Your example and this text doesn't make much sense. Then again, I'm comparing it to C/C++ globals so that could be the flaw in my reasoning. If the global variable only holds for the current code block and file your file has several code blocks, then doesn't the purpose of global become defeated?
Beginner in Game Development?  Read here. And read here.  
Ra
Ra
Quote:
Original post by Alpha_ProgDes
I'm confused:
Quote:
Python says:
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

Your example and this text doesn't make much sense. Then again, I'm comparing it to C/C++ globals so that could be the flaw in my reasoning. If the global variable only holds for the current code block and file your file has several code blocks, then doesn't the purpose of global become defeated?


The global statement is used to allow access to a global variable, not to declare one. You use the global statement in the code block (corresponds directly to indentation level) to enable access to that variable as opposed to creating a new one with the same name inside the current block.

hurr = 10           # create variabledef foo():        global hurr # let pythong know we want the global hurr                hurr = 20   # normally this would create /another/ hurr, but since we used global it will access the existing one
Ra
Alpha_ProgDes
Alpha_ProgDes
ahhhhh, it's like a scope resolution operator. gotcha!
I gave you a late Christmas present [smile]
Beginner in Game Development?  Read here. And read here.  

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.