Python global keyword

The global keyword in Python is used to declare that a variable inside a function refers to the global scope, enabling the function to modify or access the global variable directly.

Example

count = 0  # Global variable

def increment():

    global count  # Declare count as global

    count += 1  # Modify the global variable

increment()

print(count)  # Output: 1

Syntax

global variable_name
  • variable_name: The name of the variable being declared as global.

Why Use global?

  1. Modify Global Variables in Functions: By default, variables inside functions are local. The global keyword allows a function to modify global variables.
  2. Share Data Between Functions: Enables multiple functions to access and update the same global variable.
  3. Control Variable Scope Explicitly: Makes it clear that a variable belongs to the global scope.

Common Examples

1. Counter Example

A global counter updated across multiple function calls.

counter = 0

def increment_counter():

    global counter

    counter += 1

increment_counter()

increment_counter()

print(counter)  # Output: 2

2. Global Flags

Using a global flag to control program behavior.

is_active = False

def activate():

    global is_active

    is_active = True

activate()

print(is_active)  # Output: True

3. Sharing Data Across Functions

score = 0

def add_points(points):

    global score

    score += points

def display_score():

    print(f"Score: {score}")

add_points(10)

display_score()  # Output: Score: 10

This structure includes a definition, a relatable common example, the syntax, reasons why to use it, and common examples that demonstrate its utility in practical scenarios.

Leave a Comment

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

Scroll to Top