Saturday, July 24, 2010

python: local vs global scope

What are the rules for local and global variables in Python?


In Python, variables that are only referenced (and not assigned a value) inside a function are implicitly global.

If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local.

If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it with the "global" keyword if you want to use the global context.

No comments: