-1

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.

3 Answers3

2

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()
Shivam Singh
  • 1,584
  • 1
  • 10
  • 9
0

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
Shubham
  • 2,847
  • 4
  • 24
  • 37
0

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.

Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
  • This should be the accepted answer, since it avoids the global variable, which is preferable. – Zinki May 22 '18 at 07:29
  • But this `delay` is still a global, it's just that it's being modified by global code, not code inside a function. – PM 2Ring May 22 '18 at 07:32
  • It is modified in its own context, `global` is used to modify global variables in local context, which makes things more complex (usually with no need). The other added value is that `foo` is now a function of its' parameters and does not depend on an external state (easier to reason about, easier to test and debug). – Reut Sharabani May 22 '18 at 07:41