Why does this code doesn't give any error?
travel_log = [
{
"country": "France",
"visits": 12,
"cities": ["Paris", "Lille", "Dijon"]
},
{
"country": "Germany",
"visits": 5,
"cities": ["Berlin", "Hamburg", "Stuttgart"]
},
]
# compare this **code block 1** with code block 2 and 3
def add_new_country(country, visits, cities) :
new_country = {}
new_country["country"] = country
new_country["visits"] = visits
new_country["cities"] = cities
travel_log.append(new_country)
add_new_country("Russia", 2, ["Moscow", "Saint Petersburg"])
print(travel_log)
But this one does? Error: Unbound Local Error: local variable referenced before assignment
#code block 2 (Replace code block 1 with this and run the code)
def add_new_country(country, visits, cities) :
new_country = {
"country" : country,
"visits" : visits,
"cities" : cities,
}
travel_log += new_country
why is the error gone after making travel_log variable global? and why did the code work even if we didn't make the variable global in code block 1
#code block 3 (Replace code block 1 with this and run the code)
def add_new_country(country, visits, cities) :
global travel_log
new_country = {
"country" : country,
"visits" : visits,
"cities" : cities,
}
travel_log += new_country