Python Scope
- Previous Page Python Iteration
- Next Page Python Modules
Variables are only available within the area they are created. This is called scope.
Local scope
Variables created within a function belong to the function's local scope and can only be used within that function.
Example
Variables created within a function are available within that function:
def myfunc(): x = 100 print(x) myfunc()
Functions Inside Functions
As shown in the example above, the variable x is not available outside the function, but is available to any function inside the function:
Example
Can access local variables from a function inside a function:
def myfunc(): x = 100 def myinnerfunc(): print(x) myinnerfunc() myfunc()
Global Scope
Variables created in the main body of Python code are global variables, belonging to the global scope.
Global variables are available in any scope (global and local).
Example
Variables created outside the function are global variables, which anyone can use:
x = 100 def myfunc(): print(x) myfunc() print(x)
Named Variable
If you operate on the same-named variable inside and outside the function, Python will treat them as two separate variables, one available in the global scope (outside the function), and one available in the local scope (inside the function):
Example
This function will print the local variable x, and then the code will also print the global variable x:
x = 100 def myfunc(): x = 200 print(x) myfunc() print(x)
Global Keyword
If you need to create a global variable but are stuck in the local scope, you can use the global keyword.
The global keyword makes a variable a global variable.
Example
If you use the global keyword, then the variable belongs to the global scope:
def myfunc(): global x x = 100 myfunc() print(x)
Additionally, if you want to change a global variable inside a function, please also use the global keyword.
Example
To change the value of a global variable inside a function, use the global keyword to refer to that variable:
x = 100 def myfunc(): global x x = 200 myfunc() print(x)
- Previous Page Python Iteration
- Next Page Python Modules