Home > Software engineering >  How can I increment a variable inside a function without using global variable please?
How can I increment a variable inside a function without using global variable please?

Time:01-25

I need a way to print a timer every second and execute an action every 10 seconds. The output of the program should be like below.

Timer is 1
Timer is 2
Timer is 3
Timer is 4
Timer is 5
Timer is 6
Timer is 7
Timer is 8
Timer is 9
Timer is 10
Action is executed
Timer is 1
Timer is 2
Timer is 3
Timer is 4
Timer is 5
Timer is 6
Timer is 7
Timer is 8
Timer is 9
Timer is 10
Action is executed
Timer is 1
Timer is 2
Timer is 3
. . .

The program should use threading. It should not be an infinite while loop.

I could have done it with below code but it uses a global variable. How can I do it without using a global variable and with a small amount of code like below.

import threading
import time

global MytTimer
MytTimer=0
def foo():
    global MytTimer
    MytTimer=MytTimer 1
    print("Timer is "   str(MytTimer))
    threading.Timer(1, foo).start()
    if MytTimer >= 10:
        MytTimer=0
        print("Action is executed")        

foo()

CodePudding user response:

You could create a ticker thread that delivers values 1-10 to a queue, and then a consumer that executes an action whenever the value read from the queue is 10:

import threading
import time
import queue

def foo():
    q = queue.Queue()

    def ticker():
        while True:
            for i in range(1,11):
                print(f'Timer is {i}')
                q.put(i)
                time.sleep(1)

    t_ticker = threading.Thread(target=ticker)
    t_ticker.start()

    while True:
        i = q.get()
        if i == 10:
            print("Action is executed")        

foo()

CodePudding user response:

I did it by creating a class.

import threading
import time

class count():
    def __init__(self, MytTimer):
        self.MytTimer = MytTimer
        self._run()
    def _run(self):
        threading.Timer(1, self._run).start() 
        self.MytTimer  = 1
        print("Timer is "   str(self.MytTimer))
        if self.MytTimer >= 10:
            self.MytTimer=0
            print("Action is executed") 
        
a=count(MytTimer = 0) 
  • Related