Sometimes you may need to pause or delay execution in python. Python provides a useful sleep method to paus execution. In this article, we will learn how to sleep execution in python. You can also use this to sleep function in Python.
How to Sleep Function in Python
Python comes pre-built with time module. It provides sleep function which has the following syntax.
In the above function, you need to provide the number of seconds you want to pause execution in python.
Here is an example to pause execution for 3 seconds.
import time print("hello") time.sleep(3) print("world")
You can also use it in a python function as shown below.
import time def hello_world(): print("Hello") time.sleep(3) print("World")
When you run the above function, you will see that it prints ‘world’ only 3 seconds after it prints ‘hello’ indicating that the execution was paused for 3 seconds.
You can use sleep function in any python function or code that is to be executed, as long as you import time module in it.