What's wrong in this code?


#1


#2

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


#3

could you explain this in simpler words?


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

#5

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


#6

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)


#7

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


#8

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

#9

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