0

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...?

3
Contributors
6
Replies
7
Views
8 Years
Discussion Span
Last Post by max.yevs
0

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

0

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.

0

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()
0

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.

0

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.

0

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 :(

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.