Local and Global Variables
A global variable is created in the main program, outside every sub program, so any part of the program can use it. It is the sensible choice when a value really is needed by lots of the program: if several sub programs must know the same setting, or all work on the same running total, going global saves you passing it in over and over, and any sub program can read it without being handed anything. The code stays short and easy to follow.
club_name = "Riverside Runners" # one setting the whole program follows
def welcome(name):
print("Welcome to " + club_name + ", " + name)
def cheer(name):
print(club_name + " cheers for " + name)
welcome("Ada")
cheer("Ada")Output:
Welcome to Riverside Runners, Ada
Riverside Runners cheers for Ada
Because a global belongs to the whole program, any part of the program can change it. If it ends up holding the wrong value, there is no easy way to tell which sub program put it there, so the program is harder to debug. It is also harder to maintain, because an edit inside one sub program can affect code written somewhere else entirely. A global lasts from the moment it is created until the program ends, so it occupies memory for the whole run, even while nothing is using it at that moment. Globals are not always a mistake, though — the problem is having many of them.
Pass values into a sub program as parameters and send results back out with return values. The sub program then depends on nothing outside itself, so you can test it in isolation and drop it into a different program without changing a line. Keep globals for the few values genuinely needed everywhere, and write any fixed value as a constant with a name in capitals, such as POSTAGE = 2.75, so the capitals warn everyone that it must not be reassigned.
def lap_total(lap1, lap2):
return lap1 + lap2
morning = lap_total(48, 51)
evening = lap_total(47, 52)
print("Total seconds: " + str(morning + evening))Output:
Total seconds: 198 OCR GCSE Computer Science · Local and Global Variables