Scope
A variable that you create inside a function is local to that function. This means it exists only inside the function. Parameters are local too.
The clearest way to update a value with a function is to pass the value in and return the new result.
def add_points(score, points):
return score + points
score = 10
score = add_points(score, 5)
print(score)
Output:
15
add_points receives score and points and returns their sum. The main program then stores that result back in score.
Changing an outside variable goes wrong
A function can read a variable from the main program (the code outside any function). But if the function assigns a value to that variable anywhere inside it, Python treats the variable as local in the whole function:
total = 0
def add_sale(amount):
total = total + amount
return total
print(add_sale(40))
Output:
Traceback (most recent call last):
File "/box/main.py", line 7, in <module>
print(add_sale(40))
^^^^^^^^^^^^
File "/box/main.py", line 4, in add_sale
total = total + amount
^^^^^
UnboundLocalError: cannot access local variable 'total' where it is not associated with a value
Line 4 assigns to total, so inside the function total is a new local variable. It is not the total from the main program. When Python works out the right side, total + amount, the local total has no value yet. That causes the error.
Python has a global keyword that would let the function change the outer total. But then the function changes something you cannot see when you read the call. It is better to pass the value in and return the result, as the first example does. Then every change is easy to see.
In the exercise, fix the sales function by passing the total in. Do not use global.