Home > Software engineering >  Is there a way to time a "While" loop? (Python)
Is there a way to time a "While" loop? (Python)

Time:08-13

I started teaching myself python a few days ago and today I was trying to make a "while" loop. However, it repeats itself very fast and I was looking for a way to slow it down.

def cursor():
    global cursors
    cursors  = 1
    while 1 == 1:
        print("test")

I am using "print(test) as a placeholder for what I need looped. It should print 'test' then wait for a second or two and print test again forever.

I would use a "for" loop but I don't know how to make it continue infinitely.

CodePudding user response:

You could just use time.sleep() within your loop. For example:

import time
def cursor():
    global cursors
    cursors  = 1
    while 1 == 1:
        print("test")
        time.sleep(5)

Whereas the number in the brackets is the amount of seconds to pause your loop.

CodePudding user response:

The library time can be used to pause (in seconds)

import time
cursors = 0

def cursor():
    global cursors
    while True:
        cursors  = 1
        print("test")
        time.sleep(1)    #pause 1 second
        if cursors == 10:    #break after 10 seconds
            break
        

You could also to specify another break condition to exit the loop

  • Related