Because you assigned to travel_log
in your add_new_country
function (+=
is an assignment), it is considered a local variable in that function. Because it is a local variable, and you never assigned it a value, travel_log
has no value when you attempt to +=
to it. Python does not fall back to using the global variable of the same name.
This is somewhat surprising because the +=
operation on a list is equivalent to calling its extend()
method, and the name remains bound to the same list. The error feels more reasonable when the variable is a number or some other immutable object. But it's the same behavior.
If you want to operate on the global variable, say so:
def add_new_country(countries_visited, times_visited, cities_visited):
global travel_log
# etc.
But it's better to use travel_log.append()
. Appending isn't an assignment, so it doesn't make travel_log
local.