Python Language
Python - Variable Scope:
Variable scope refers to the region of a program where a variable is accessible. Understanding scope is crucial for writing clean, bug-free code. In Python, there are mainly two types of variable scope: global scope and local scope.
1. Global Scope:
⤏ Variables declared outside of any function or class have global scope.
⤏ They can be accessed from anywhere within the program, including inside functions and classes.
⤏ To modify a global variable from within a function, you need to use the 'global' keyword.
1 | # Python variable scope: Global |
2 | x = 10 # Global variable |
3 |
|
4 | def func(): |
5 | print(x) # Accessing global variable |
6 |
|
7 | func() # Output: 10 |
10
2. Local Scope:
⤏ Variables declared within a function or a class have local scope.
⤏ They can only be accessed from within that function or class.
⤏ Variables with the same name can exist both globally and locally without affecting each other.
1 | def func(): |
2 | y = 20 # Local variable |
3 | print(y) |
4 |
|
5 |
|
6 | func() # Output: 20 |
7 |
|
8 | # Accessing local variable outside the function will result in NameError |
9 | print(y) # NameError: name 'y' is not defined |
[Error] NameError: name 'y' is not defined
However, Python also supports a concept called "enclosing scope," which comes into play with nested functions. In the case of nested functions, a variable declared in an outer function is accessible in the inner function.
1 | # Python variable scope: Local |
2 | def outer_func(): |
3 | z = 30 # Enclosing scope variable |
4 |
|
5 | def inner_func(): |
6 | print(z) # Accessing enclosing scope variable |
7 |
|
8 | inner_func() |
9 |
|
10 | outer_func() # Output: 30 |
30
Note: You can also use the 'nonlocal' keyword, which allows you to modify variables in the enclosing scope from within nested functions.
1 | nonlocal x |
2 | x = 20 # Modifying variable in the enclosing scope |
What's Next?
We've now entered the finance section on this platform, where you can enhance your financial literacy.