Functions
Every variable has a scope: the part of a program where that variable can be seen and used. Where you create a variable decides whether it is local or global.
A variable created inside a subprogram is local to it. It is created when the subprogram is called and thrown away when the subprogram ends, and only the code inside that subprogram can use it. Parameters are local too: each value you pass in is copied into a local variable. Try to use a local variable anywhere else and Python raises a NameError, because the variable no longer exists. This keeps each subprogram self-contained: two subprograms can both use a local variable called count without interfering with each other, and a change in one part of a program cannot silently break another.
A global variable is created in the main program, outside every subprogram. It can be read anywhere in the program, including inside subprograms. However, if you assign to it inside a subprogram, Python creates a new local variable instead — unless you declare it with the global keyword first, which tells Python you mean the one in the main program.
lives = 3 # global variable, created in the main program
def lose_life():
global lives # use the global variable, not a new local one
lives = lives - 1
lose_life()
print("Lives left: " + str(lives))Output:
Lives left: 2If a local variable has the same name as a global variable, they are completely separate variables held in separate places. Changing the local one does not change the global one, and the global value is still there once the subprogram has finished.
points = 50 # global variable
def bonus_round():
points = 200 # local variable with the same name
print("Inside the subprogram: " + str(points))
bonus_round()
print("Back in the main program: " + str(points))Output:
Inside the subprogram: 200
Back in the main program: 50 Edexcel GCSE Computer Science · Functions
Edexcel GCSE Computer Science · Global & Local Variables