When writing functions we might have variables that are declared within the body of a function. For instance, if a variable name is declared in the function, it’s considered a new variable, which is totally different from the one declared outside the function:
name = 'Helen'
def greet():
name = 'Bob'
print('Hi', name)
greet() # Hi Bob
print('Outside:', name) # Outside: Helen
The variable name is declared in the greet() function and its scope is up until the end of the function. Variables declared within some scope are usually referred to as local variables. As soon as the program exits the function, it “forgets” about that variable.
To access and modify the variables outside of the current scope, we can use the global keyword to tell Python that we would like to treat that variable as global:
name = 'Helen'
def greet():
global name
name = 'Bob'
print('Hi', name)
greet() # Hi Bob
print('Outside:', name) # Outside: Bob
This time the greet() function modified the global name variable and changed its value to Bob.
Challenge
Given the following function, try to find the mistake and fix it. The function should return the sum of values passed to it so far.
total = 0
def compute_sum(val):
total = total + val
return val
print(compute_sum(10))
print(compute_sum(20))
print(compute_sum(30))