How to add 1 to a number every 2 minutes?

Viewed 136

How can I add 1 to a variable every 2 minutes it until reaches 100.

The program will start the number from 0 and it will add every 1 number in every 2 minutes until it reaches 100.

         2 min later
0/100     ------>       1/100
5 Answers

Use sleep function from time module

from time import sleep

i = 0
while i <= 100:
   sleep(120)
   i += 1

If you need to make a progressbar, you can also check tqdm.

from tqdm import tqdm
import time

for _ in tqdm(range(100)):
   time.sleep(120)

One line solution:

from time import sleep
for t in range(100): time.sleep(120)

I used sleep!

from time import sleep

for i in range(100):
    sleep(120)
    # print(i)

I believe all solutions presented so far are thread locking??

import asyncio, time

async def waitT(tWait, count):
    print(count)
    while count < 100:  #The 100 could be passed as a param to make it more generic
        await asyncio.sleep(tWait)
        count = count + 1
        print(count)
    return

async def myOtherFoo():
    #Do stuff in here
    print("aaa")
    await asyncio.sleep(2)
    print("test that its working")
    return

async def main(count):
    asyncio.gather(myOtherFoo(), waitT(120, count))  #Obviously tweak 120 to whatever interval in seconds you want
    return

if __name__ == "__main__":
    count = 0
    asyncio.create_task(main(count))
    

A simple, and hopefully readable, async solution. Doesn't check for running loops etc - but should open you up to a range of possibilities for acting between each update in your counter.

Related