What's wrong in this code?



Your function has a local variable t that is used before it has been assigned


could you explain this in simpler words?

a = a  # <- Can't define a as a before having defined a


i mean if i had defined t = 0 and used a for loop. what does reference before assignment mean?


It means you’re reading it before having created it

Your variable t which you’ve given the value 0 is a different variable. You’re using the t that exists in your function.

There are several other bugs too, the first being that you shouldn’t have a global value t at all (if you call your function more than once it’ll remember old results), and a second bug is that your loop isn’t a loop at all because during each iteration you exit the function completely (so you’ll never do a second iteration)


how can it be different ? t is the alphabet which is same everywhere. I can’t understand


No, variables do not exist everywhere. You have one t in your module, and another in your function.

For example:

def f():
    a = 5

f()  # this doesn't create the variable a at module level
print a  # error, a undefined


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.