A variable scope specifies the region where we can access a variable.
Local Scope and Local Variables
- A local variable is a variable that is only accessible from within a given function. Such variables are said to have local scope.
- In Python, any variable assigned a value in a function becomes a local variable of the function.
Example
Consider the following example where two functions, func1 and func2, each have a local variable named a:
def func1():
a = 5 # Local variable 'a' in func1
print("func1 - a:", a)
def func2():
a = 10 # Local variable 'a' in func2
print("func2 before func1 call - a:", a)
func1()
print("func2 after func1 call - a:", a)
func2()
Output
func2 before func1 call - a: 10
func1 - a: 5
func2 after func1 call - a: 10
- Each function has its own local variable
a. - The value of
ainfunc2is not affected by the value ofainfunc1and vice versa. - Calling
func1withinfunc2does not change the local variableainfunc2.
If we remove the assignment of n in func1, it will result in an error because n is not defined within the scope of func1
Lifetime of Local Variables
- The period of time that a variable exists is called its lifetime.
- Local variables are automatically created (allocated memory) when a function is called and destroyed (deallocated) when the function terminates.
- Thus, the lifetime of a local variable is equal to the duration of its function’s execution.
- Consequently, the values of local variables are not retained from one function call to the next.
Global Variables and Global Scope
- A global variable is defined outside any function and can be accessed from multiple functions.
- It has global scope, meaning it's available throughout the entire program.
Example
max_value = 100 # Global variable
def func1():
print("func1 - max_value:", max_value)
def func2():
print("func2 - max_value:", max_value)
func1()
func2()
Output
func1 - max_value: 100
func2 - max_value: 100
max_valueis defined outsidefunc1andfunc2, making it a global variable.- Both
func1andfunc2can access and printmax_valuedirectly.