import time # Pause for 5 seconds time.sleep(5)
To create a time delay in Python, you can use the time.sleep() method, which will pause the execution of your program for a specified number of seconds.
The above code will pause the program for 5 seconds before continuing. You can use a decimal value (e.g. 0.5) to specify a fractional number of seconds, if needed.
It's important to note that the time.sleep() method blocks the execution of your program, which means that your program will not do anything else while the delay is happening. If you want to create a delay without blocking the execution of your program, you can use the threading module's Timer class to create a timer that will execute a specified function after a certain amount of time has passed. Here's an example:
import threading # This function will be called after the delay def my_function(): print('Hello, world!') # Create a timer that will call 'my_function' after 5 seconds timer = threading.Timer(5, my_function) # Start the timer timer.start()
In this example, the my_function() function will be called after a delay of 5 seconds. The time.sleep() method is not used, so the program will continue to run and do other things while the delay is happening. When the delay is over, the my_function() will be called in a separate thread, so it will not block the execution of the rest of the program.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.
Subscribe to be the first to know when a new Python course is released.