Apologies, so to clarify the difference, in your first function you are trying to modify the variable using an operator. This is where the issue lies when using global variable, as you can access it and display the value, like you do with the budget code. However you cannot modify it without using the
global keyword like I did. Otherwise it tries to find a global variable to modify, cannot and throws the error. You can notice this if we modify your budget code:
budget = 1000
# Here we are using a default value for our parameter of `destination`
print(" Looks like you're going to " + destination)
print(" Your budget for this trip is " + str(budget))
budget -= 50
This throws an error for line 6, because as soon as you try to modify the variable aka. assign to the variable at all within the function, it makes it a local variable. Therefore the function is seeing the local variable assigned on line 7, but the local variable is referenced on line 6 now which is producing the error. But if we never attempt to assign the variable in the function, it works perfectly, as it looks to the global variable.
Now if we look at your first code, we can change this to:
counter = 0
for num in nums:
if num % 10 == 0:
counter = 1
print(divisible_by_ten([20, 25, 30, 35, 40]))
Notice how this works, but the print on line 12 gives 0, whilst the one returned from the function gives 1. That’s because these are now two different variables, and we are simply creating a new local variable called
counter. Now replace
counter = 1 with
counter += 1 and see how it throws the error now? It’s trying to reference a local variable counter as part of the modification, however no such variable has been initialised. Therefore it now no longer works.
The big summary of this is essentially that you cannot modify global variables inside functions without using the
global keyword to initialise them in the function. If you just want to use them to modify a new, local variable, or to print their value that’s all acceptable. But a global variable cannot be modified unless the global keyword is used to initialise it first.