Local vs Global Variables: What’s the Difference?
Learn the difference between local and global variables, see a simple code example, and understand why variable scope matters in GCSE Computer Science.
A local variable is created inside a function or procedure and can normally be used only there. A global variable is defined outside functions and can be accessed from different parts of a program. The key difference is scope: the part of the program where a variable can be used.
A simple example
score = 10 # global variable
def show_score():
bonus = 2 # local variable
print(score + bonus)
show_score() # prints 12
print(score) # prints 10
The function can read score because it is global. It can also use bonus because bonus is local to that function. But trying to use bonus after the function call, outside the function, would cause an error: it is not defined there.
Why does it matter?
Local variables keep information contained within the function that needs it. This makes code easier to understand because other parts of the program cannot accidentally change those variables. A local variable is usually available only while its function is running.
Global variables are useful when several parts of a program need the same value. However, if different functions change a global variable, it can become harder to work out where an unexpected value came from. Use a local variable when a value is needed in just one function; use a global variable only when sharing that value across the program is necessary.
Common exam mistake: Do not say that a variable is local simply because it appears near a function. Check where it is defined and where it can be accessed. In the example, score is used inside show_score(), but it is still global because it was defined outside the function.