DevAcademia
C++C#CPythonJava
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz
  • Python Fundamentals

  • Introduction to Python
  • Getting Started with Python
  • Python Syntax
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Numbers
  • Python Casting
  • Python Strings
  • Python Booleans
  • Python Operators
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python If...Else
  • Python Match
  • Python While Loops
  • Python For Loops
  • Python Functions
  • Python Lambda
  • Python Arrays
  • Python OOP

  • Python OOP
  • Python Constructors
  • Python Destructors
  • Python Classes/Objects
  • Python Inheritance
  • Python Polymorphism
  • Python Quiz

  • Python Fundamentals Quiz

Loading Python tutorial…

Loading content
Python FundamentalsTopic 9 of 77
←PreviousPrevNextNext→

Global Variables

Understanding Scope

A global variable is defined outside of all functions and is accessible throughout the module. Functions can read global variables directly, but modifying them requires special handling.

⚠️ Warning: Reading global variables works by default. To modify them inside a function, you must explicitly declare them with the global keyword.
Example
count = 0  # Global variable

def increment():
    print(count)  # Can read global

increment()      # Output: 0
Output
0

The global Keyword

The global keyword allows a function to modify a variable declared outside its scope. Without it, Python creates a new local variable instead of modifying the global one.

Example
total = 0

def add_to_total(amount):
    global total  # Declare we're using the global variable
    total += amount
    print(f"Total is now {total}")

add_to_total(10)
add_to_total(20)
Output
Total is now 10
Total is now 30
ℹ️ Note: Avoid unnecessary use of global when values can be passed as parameters or returned instead.

Best Practices

Global variables should be used sparingly. They are more suitable for constants or configuration values than for frequently updated state. The table below shows recommendations.

DoDon't
Use for constantsUse for frequently changed state
Make names uppercaseRely on them for function communication
Document thoroughlyUse across many unrelated modules
Consider alternativesUse as default function parameters

Alternatives to global variables include:

- Class attributes

- Function parameters and return values

- Configuration objects or modules

- Singleton or dependency injection patterns

Advanced Patterns

In larger applications, global-like values are often managed through configuration modules. This improves readability and avoids scattering global state across files.

Example
# Config module pattern
# config.py
DEBUG = True
API_KEY = '12345'

# main.py
import config

def connect():
    if config.DEBUG:
        print("Debug mode enabled")
    # Use config.API_KEY here

# Runtime modification
import config as cfg
cfg.DEBUG = False
ℹ️ Note: This pattern centralizes configuration values, making code cleaner and easier to maintain than using raw globals.
Test your knowledge: Global Variables
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
Python FundamentalsTopic 9 of 77
←PreviousPrevNextNext→