Header Ads Widget

Ticker

6/random

Python Scope

Python Scope

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:

```python
global_variable = 10 # Global variable

def print_global_variable():
    print(global_variable) # Accessing global variable

print_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:

```python
def print_local_variable():
    local_variable = 5 # Local variable
    print(local_variable) # Accessing local variable

print_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:

```python
def add_numbers(a, b):
    result = a + b # Local variable within the function
    return result

sum_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:

```python
def outer_function():
    outer_variable = "I am outer"

    def inner_function():
        inner_variable = "I am inner"
        print(outer_variable) # Accessing outer_variable from the inner function
        print(inner_variable)

    inner_function()

# Accessing outer_function which indirectly accesses outer_variable and inner_variable
outer_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:

```python
global_var = 10

def modify_global():
    global global_var
    global_var = 20 # Modifying the global variable within a function

modify_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.

Understanding scope is crucial for writing maintainable and error-free code. It helps in avoiding naming conflicts and ensures that variables are accessed where they are intended to be.

Post a Comment

0 Comments