Local and Global Variables in Python

Mannan Ul Haq
0
Variables in Python are classified into two main types based on their scope: local and global.

1. Local Variables:

Definition: A variable declared inside a function or method is called a local variable. It is only accessible within the function or method in which it is defined.

Lifetime: The lifetime of a local variable lasts only as long as the function is executing. Once the execution of the function is done, the variable is destroyed.

Example:

def example_function():
    local_variable = "I'm a local variable"
    print(local_variable)

In the above example, `local_variable` is a local variable, and it can only be accessed within `example_function`.

NOTE: A local variable can have the same name as a global variable, but within the function, the local variable takes precedence.

2. Global Variables:

Definition: A variable declared outside of any function, class, or method is called a global variable. It has a global scope, meaning it can be accessed from any function or method.

Accessibility: If a variable is defined as global, it can be read from a function without declaring it, but to modify it, you'd need to use the `global` keyword inside the function.

Example:

global_variable = "I'm a global variable"

def example_function():
    global global_variable
    global_variable = "Modified global variable"
    print(global_variable)

In the above example, `global_variable` is a global variable, and it is modified within `example_function`.

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !