How to use the sleep() function in Python
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 thetimemodule in Python.
Syntax
The syntax of the sleep() function is given below:
time.sleep(delay)
Parameter
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.
Example
The code below shows how a sleep() function works:
One-second sleep
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..")
Sleeping for four and a half seconds
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()
Conclusion
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.
Free Resources