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 the time module in Python.

How to work the time.sleep() function

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 module
import time
print("Starting... \n")
time.sleep(1) # Sleeping for one second
print("Back to the future..")

Sleeping for four and a half seconds

This program sleeps for 4.5 seconds before printing “Educative.”

# Importing time module
import time
def startFunc():
print("Starting...\n")
def endFunc():
print("Educative")
def main():
startFunc()
time.sleep(4.5) # Sleeping for 4.5 second
endFunc()
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.

Copyright ©2024 Educative, Inc. All rights reserved