In Python, variables can have different scopes, primarily local and global. The scope of a variable determines where in the code it can be accessed and modified. Here are some examples and exercises to illustrate the concept of local and global scope:

Global Scope: A variable defined outside of any function or block has a global scope. It can be accessed and modified from anywhere in the code.


global_var = 10

def print_global():
    print("Global variable:", global_var)

print_global()  # Output: Global variable: 10

def modify_global():
    global global_var
    global_var += 5

print("Modified global variable:", global_var)  # Output: Modified global variable: 15

Local Scope: A variable defined inside a function has a local scope. It can only be accessed and modified within that function.


def local_scope_example():
    local_var = 5
    print("Local variable:", local_var)

local_scope_example()  # Output: Local variable: 5

# Trying to access local_var outside the function will result in an error
# print(local_var)  # This will raise a NameError


  1. Create a global variable x with a value of 20. Write a function multiply_by_2 that takes an argument num and multiplies it by the global variable x. Call the function with an argument of 5 and print the result.
  2. Write a function outer_function that defines a local variable y with a value of 10. Inside outer_function, define another function inner_function that prints the local variable y. Call outer_function and then call inner_function from within it.
  3. Create a global variable total with an initial value of 0. Write a function add_to_total that takes an argument num and adds it to the global variable total. Call the function multiple times with different values and print the final value of total after all calls.
  4. Define a variable message with a string value in the global scope. Write a function print_message that prints the message variable. Inside the function, define a local variable message with a different string value and print it. Call print_message and observe the output.

These exercises will help you understand and practice working with local and global variable scopes in Python.

One Response

Leave a Reply

Your email address will not be published. Required fields are marked *