Local and Global Variables
Sometimes the main program and a sub program both use the same variable name, and the sub program assigns a value to it. Which variable the name means inside the sub program depends on one thing: whether the sub program contains a global statement for that name.
When the sub program assigns to the name without a global statement, Python creates a new local variable with that name. Every use of the name inside that sub program then refers to the local variable, not the global one. The global variable is left completely alone, so after the sub program ends it still holds its original value, even though the sub program appeared to change it.
bottles = 24
def count_crate():
bottles = 30
print("In the crate:", bottles)
count_crate()
print("In the cupboard:", bottles)Output:
In the crate: 30
In the cupboard: 24
If the sub program starts with global followed by the name, there is only one variable: the shared global. Assigning to the name inside the sub program changes that single variable, so the new value is still there after the sub program ends and the main program prints it.
bottles = 24
def count_crate():
global bottles
bottles = 30
print("In the crate:", bottles)
count_crate()
print("In the cupboard:", bottles)Output:
In the crate: 30
In the cupboard: 30
To work out what a program with a name clash prints, trace each use of the name separately. First ask whether a global statement for that name appears at the start of the sub program. If it does, every use inside is the global. If it does not, an assignment inside the sub program makes the name local throughout that sub program, so every use inside is the local. Then follow the values line by line, and for each print statement write down the value and the reason: local or global.
OCR GCSE Computer Science · Local and Global Variables