In Python, the scope refers to the region of code where a variable or a name is accessible. There are two main types of scope in Python: global scope and local scope.
Here's an explanation with examples:
1. Global Scope:
```pythonglobal_variable = 10 # Global variabledef print_global_variable():print(global_variable) # Accessing global variableprint_global_variable()```
In this example, `global_variable` is defined in the global scope, making it accessible within the function `print_global_variable`. Variables defined outside any function or class have global scope.
2. Local Scope:
```pythondef print_local_variable():local_variable = 5 # Local variableprint(local_variable) # Accessing local variableprint_local_variable()# This will result in an error because local_variable is not accessible outside its scope# print(local_variable)```
The `local_variable` is defined within the `print_local_variable` function, making it accessible only within that function. Trying to access it outside the function will result in an error.
3. Function Parameters:
```pythondef add_numbers(a, b):result = a + b # Local variable within the functionreturn resultsum_result = add_numbers(3, 5)print(sum_result)```
The parameters `a` and `b` in the `add_numbers` function have local scope within the function. The `result` variable is also local to the function.
4. Nested Scopes:
```pythondef outer_function():outer_variable = "I am outer"def inner_function():inner_variable = "I am inner"print(outer_variable) # Accessing outer_variable from the inner functionprint(inner_variable)inner_function()# Accessing outer_function which indirectly accesses outer_variable and inner_variableouter_function()```
In this example, `inner_function` has access to both its local variable (`inner_variable`) and the variable in the enclosing scope (`outer_variable`). This demonstrates nested scopes.
5. Global Keyword:
```pythonglobal_var = 10def modify_global():global global_varglobal_var = 20 # Modifying the global variable within a functionmodify_global()print(global_var) # Outputs: 20```
The `global` keyword allows modifying a global variable within a function. Without `global`, Python would create a local variable instead.
0 Comments