Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to break the program after my time completed in python?

I have a program to stop the for loop, even though the loop is running. I want to exit from this loop once my timer is over.

Ex: Timer set to = 10 seconds

def Start_function():
    timer = 10 seconds
    for i in range(60):
      print(i)
      time.sleep(1)
    return

Here loop will continue executing till for loop completion. But I need to exit from this function once the time is reached 10 seconds.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

please help me out on this program.
Thanks in advance.

Find the below program:

import threading import time def demo(): print("Start function\n") for i in range(60):  print(i, end=" ") time.sleep(1) def thread_cancel(): time.sleep(5)
timer.cancel()
print("Yes ") timer = threading.Timer(1, gfg) timer.start() print("Cancelling timer\n") thread_cancel()  print("Exit\n")

>Solution :

You can simply add an if condition to check if i == timer: and then return to terminate the program.

import time
def Start_function():
    timer = 10
    for i in range(60):
        if i == timer:
            return "Timer ran successfully"
        print(i)
        time.sleep(1)

Output:

0
1
2
3
4
5
6
7
8
9
'Timer ran successfully'

But this is a bad implementation of a timer. You can improve by:

def Start_function(timer):
    for i in range(timer):
        time.sleep(1)
        print(i)

Start_function(10) # This starts the timer for 10 second 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading