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 give me 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, shouldn't it just loop...?

sorry i think i accidently double posted, i'll mark this thread as solved. (or maybe moderator can delete it?)

You need to stop recursing your main function, it's going to get you in trouble. Here's an example using a while loop.

import time

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

EDIT: I didn't notice the other thread about this same problem, in which it is already solved.

Member Avatar for leegeorg07

also you might want to add a return function(

import time

def main():
    a = 0
    while True:
        print (a)
        time.sleep(5)
        a += 1
        return a
    
main()

also you might want to add a return function(

import time

def main():
    a = 0
    while True:
        print (a)
        time.sleep(5)
        a += 1
        return a
    
main()

This will exit the main function on the first iteration of the while loop. I would suggest that you do not do this.

Member Avatar for leegeorg07

would it?, i never knew that, i guess ive got to edit a lot of code, that could be why they didnt do what i expected.

not sure what return does...
but thanks jim i've already adopted that counter from the other post...

and yeah, sorry for making two posts... i was editing the code brackets to code=python for python syntax and somehow it doubled :(

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.