The sleep()
function suspends the current thread’s execution for seconds. In the case of a single-threaded program, it suspends the thread and the program (as only one thread is also suspended).
Note: The
sleep()
function is defined in thetime
module in Python.
The syntax of the sleep()
function is given below:
time.sleep(delay)
delay
: This is the number of seconds for the execution of the Python program to be paused. This argument can be an integer
or a float.
The code below shows how a sleep()
function works:
This program sleeps for one second before printing.
# Importing time moduleimport timeprint("Starting... \n")time.sleep(1) # Sleeping for one secondprint("Back to the future..")
This program sleeps for 4.5 seconds before printing “Educative.”
# Importing time moduleimport timedef startFunc():print("Starting...\n")def endFunc():print("Educative")def main():startFunc()time.sleep(4.5) # Sleeping for 4.5 secondendFunc()main()
The sleep()
function is very important for advanced-level Python, especially for multithreading. The function helps the threads to synchronize with each other and perform their tasks at correct intervals.