Reassigning value to a variable inside a function in python

Question:

I want to run an infinite loop and at every 100th loop i want to print. If I do this : it works perfectly,

delay=0

while 1:
delay=delay+1
print(delay)
if delay>100:
    delay=0
    print('100th time')

However if I put my if statement in a function it gives error:

delay=0
def foo():
    if delay>100:
        delay=0
        print('100th time')
while 1:
    delay=delay+1
    print(delay)
    foo()

The error is : UnboundLocalError: local variable ‘delay’ referenced before assignment.

Is there anyway I can do the reassignment in a function? Putting the entire thing in my while loop would be problematic for me.

Asked By: user137273

||

Answers:

You can use global declaration inside the function as shown below:

delay=0
def foo():
    global delay
    if delay>100:
        delay=0
        print('100th time')
while 1:
    delay=delay+1
    print(delay)
    foo()

You can also avoid global in this case by passing the value in the function foo() ans reassign delay like delay = (delay + 1) % 100.

delay=1
def foo(delay):
    if delay == 0:
        print('100th time')
while True:
    delay = delay + 1
    print(delay)
    foo(delay)
    delay = delay % 100
Answered By: Shubham

You can use global, if you do not want pass delay as an argument to foo. But it is better to do it that way. Also read: Why are global variables evil?

delay=0
def foo():
    global delay
    if delay>100:
        delay=0
        print('100th time')
while 1:
    delay=delay+1
    print(delay)
    foo()
Answered By: Shivam Singh

Pass delay to the function and use modulu(%):

delay=0
def foo(delay):
    if delay % 100 == 0:
        print('100th time')

while True:
    delay=delay+1
    print(delay)
    foo(delay)

Always avoid using globals when other effective solutions exist. They increase the complexity of the code significantly.

Answered By: Reut Sharabani
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.