Exercise-33 Study Drill

I created this according to a study drill.

i = 0
numbers = []

def loop(limit):
    while i < limit:
        print(f"At the top i is {i}")
        numbers.append(i)
        i += 1
        print("Numbers now: ", numbers)
        print(f"At the bottom i is {i}")

loop(input(">>> "))

print("The numbers:")
for num in numbers:
     print(num)

But I get this error:

Traceback (most recent call last):
File " ", line 15, in
loop(x)
File " ", line 5, in loop
while i < limit:
UnboundLocalError: local variable ‘i’ referenced before assignment

Can someone please explain what is wrong?

The error is telling you that ‘i’ is used before it’s referenced. This is in the loop as the scope of i = 0 is outside of your function. Move it into the loop function as it’s the only place you use it.

You will also find you’ll get a new error based on the type of ‘limit’. See if you can figure out how to ensure the type is valid. :slightly_smiling_face:

Thanks, I also found out that I could use “global i” inside of ‘def’ to make it work.

Also, yes, I had to change the type to ‘int()’ or ‘float()’ because its type was initially as ‘string’.

Thanks for your help!

2 Likes
A free service run by Zed A. Shaw for learncodethehardway.org.