Course contentsShow
← Computer Science
Lesson 209 of 2,8725. Functions and ModularityFree lesson

Global Variables

Variables declared outside all functions that are accessible throughout the program.

Global Variables

What you'll learn: How to use variables that live outside all functions and can be accessed from anywhere in your program.

What Are Global Variables?

A global variable is a variable you declare outside of any function. Because it's not trapped inside a function's scope, it can be read (and often modified) by any function in your program.

Think of global variables like a bulletin board in a school hallway—everyone walking by can see what's posted there, unlike notes kept private inside individual classrooms (local variables).

When You Might Use Them

Global variables are useful for data that multiple functions need to share:

# Global variable - declared outside all functions
game_score = 0

def award_points():
    global game_score
    game_score = game_score + 10

def display_score():
    print(game_score)

award_points()
display_score()  # Prints: 10

In this example, game_score lives at the "program level," not inside any specific function. Both award_points() and display_score() can access it.

Why Be Careful

While globals can seem convenient, they make programs harder to understand and debug. When any function can change a global variable, it's tough to track down where a value got modified. Functions with local variables are easier to reason about—they only work with what you pass in.

Key Takeaway: Global variables are declared outside all functions and accessible throughout the program, but use them sparingly—local variables and parameters usually lead to clearer, safer code.