so i was trying to make a very simple counter (although not sure if that's what you call it)

import time
a = 0
def main():
    time.sleep(5)
    b = a + 1
    print (b)
    del(a)
    a = b
    del(b)
    main()   
main()

i know this is very unefficient and there is probably some command to count, but why doesn't this work?

i thought for sure it would print the next number every 5 seconds: 1, 2, 3, 4, 5, etc.

but apparently "a is referenced before assignment" which i don't see why it's a problem, because after the first reference a = 0, it should just loop...?

sorry i think i accidently double posted when changing code to python syntax.

i'll mark the other one as solved.

Why are you using del and using a recursive function? Why are you using two variables when you are only keeping track of one number?

Try something like this:

import time
a = 0
while True:
    a += 1
    print(a)
    time.sleep(5)

My recommendation would be that you forget that del exists until you are sure that you have a good use for it.

thanks it works great...

i used del so that it would forget the prior meanings of a and b, although i know its unnecesary since meaning automatically changes.

and i used two variables because i did not know that a +=1 statement and i couldn't exactly write a = a+ 1, could i?

but anyways, thanks it works great... although still can't understand why my didn't work.

thanks it works great...

i used del so that it would forget the prior meanings of a and b, although i know its unnecesary since meaning automatically changes.

and i used two variables because i did not know that a +=1 statement and i couldn't exactly write a = a+ 1, could i?

but anyways, thanks it works great... although still can't understand why my didn't work.

a += 1 is the same as a = a + 1 , which, yes, would work fine.

Your code doesn't work because a is a global variable but when you are referencing it in main(), it is treated as a local variable, which doesn't exist. You could change your code like this to get it to run:

import time
a = 0
def main():
    time.sleep(5)
    global a
    b = a + 1
    print (b)
    del(a)
    a = b
    del(b)
    main()   
main()

However, I wouldn't do this.

alright, thanks for explaining...

of course i knew from the beginning that my attempt wouldn't be the best approach... i've adopted your counter for what i needed the counter for...

so from what i understand, "while true" automatically makes a loop of everything indented below it, right?

That's right. You could change True to some other condition if you wanted the counting to stop.

This question has already been answered. Start a new discussion instead.