What is Computer

Module: M3-R5: Python Programming

Chapter: Ch1 Computer Intro

🔹 What is the global Statement?

The global statement in Python is used to declare that a variable inside a function refers to a variable defined in the global scope. It allows modification of global variables inside a function.

Syntax:

global variable_name

Example:

x = 10  # Global variable

def modify():
    global x
    x = x + 5
    print("Inside function:", x)

modify()
print("Outside function:", x)

Output:

Inside function: 15
Outside function: 15
🔹 Without Using global Keyword

If you try to modify a global variable inside a function without declaring it as global, Python creates a new local variable instead.

x = 10

def modify():
    x = x + 5  # Error! Trying to modify global variable locally
    print(x)

modify()

Output:

UnboundLocalError: local variable 'x' referenced before assignment

✅ To fix this, we must use the global keyword inside the function.

🔹 Using Multiple Global Variables
a, b = 5, 10

def update():
    global a, b
    a = a + 2
    b = b + 3

update()
print("a =", a)
print("b =", b)

Output:

a = 7
b = 13
✅ Summary
  • The global statement lets you modify global variables inside a function.
  • Without declaring as global, any assignment creates a local variable.
  • You can declare multiple variables global at once using commas.
  • Use global variables carefully to avoid confusing dependencies in code.
Quick Links