Local and global variables

Variable scope

Scope means where in a program a variable can be used or accessed. It tells us:

  • Where the variable is visible
  • How long it stays in memory

There are two common types of variable scope:

  • Local scope
  • Global scope

Local variables

A local variable is one that is only available in a specific part of the program – usually inside a subprogram like a procedure or function.

  • It is created in memory when the subprogram starts

  • It can only be used in that subprogram

  • It is removed from memory when the subprogram ends

Use local variables when you only need the data for one task or block of code.

The variable name is declared and used inside the same subprogram, so it works fine.

def greet():
    name = "Jamie"
    print("Hello, " + name)

# Main
greet()  # Output: Hello, Jamie

The variable name only exists inside the subprogram. When you try to use it outside, it causes an error.

def greet():
    name = "Jamie"

# Main
greet()
print("Hello, " + name)  # Error: name is not defined

Global variables

A global variable is created outside of all subprograms. It can be used anywhere in the program.

  • It is stored in memory as soon as the program starts

  • It can be accessed or changed by any part of the program

  • It stays in memory until the program ends

Use global variables only when you need the same value in many parts of your code.

The variable score is global and is passed into the subprogram and then returned.

def add_points(score):
    score = score + 10
    return score

# Main
score = 0  # Global variable
score = add_points(score)
print(score)  # Output: 10

The subprogram doesn’t actually reset the global high_score, because it made a new variable with the same name by mistake.

def reset_score():
    high_score = 0  # Creates a new local variable instead of updating the global one

# Main
high_score = 200  # Global variable
reset_score()
print(high_score)  # Output: 200

Comparing local and global variables

Feature Local Variable Global Variable
Scope Inside the subprogram where it is created Entire program
Accessibility Only accessible within the subprogram Accessible from any part of the program
Memory Use Created when the subprogram runs and deleted when it ends Stored in memory from start to end of the program