I'm a Python beginner, and I was curious why this one error pops up on a function but not a while loop. I think it has to do with some fundamental difference between the two, but I can't quite get my head around what that difference is. Here's my example:
I have a while loop which pulls an error of "UnboundLocalError: local variable 'cats' referenced before assignment" if I leave the variable above the function. That makes complete sense to me, so I fixed it by moving it below the function def line like below:
doesnt work:
cats = 3
def cat_down(start_number):
while (cats > 0):
print(cats)
cats -= 1
print("All cats have been adopted!")
cat_down(3)
works
def cat_down(start_number):
cats = 3
while (cats > 0):
print(cats)
cats -= 1
print("All cats have been adopted!")
cat_down(3)
However, if I run a while loop without a function - and I have the cats variable above the while loop - it runs with no errors:
cats = 3
while (cats > 0):
print(cats)
cats -= 1
print("All cats have been adopted!")
To me, this makes less sense, as the variable is outside of the code block of the while loop. Is it simply that functions are like "mini programs" that need to self contain variables - and those variables need to be in the code block in order for the function to behave correctly when called later on in the program - whereas while loops don't have those same replicating attributes? If so, why can a while loop still reference and modify the variable that's outside of its code block? I tried to Google this, but I still don't think I'm understanding the concept and I think I'm getting hung up on how the while loop can reference a variable outside of it whereas a function can't in this instance. I apologize if this is a really dumb question, and thank you in advance for any help or clarity!