How to Use the Python sleep() Function



In this article, you will learn how to use the Python sleep() function.

Python sleep() Function

The sleep() function in Python is part of the time module and is used to halt the execution of the program for a specified number of seconds.

The function takes one argument which is the number of seconds to pause the execution of the program. The argument must be a non-negative number.

During the sleep period, the program does not consume any CPU resources. This means that the sleep function does not prevent other processes from running or block any system resources.

The function is useful in many situations, such as pausing between successive iterations of a loop, waiting for a resource to become available, or adding a delay before performing an action.

Keep in mind that the sleep time is not guaranteed to be exact. The actual sleep time may be longer or shorter than the specified time due to various system and environmental factors.

The sleep() function can be interrupted by signals such as KeyboardInterrupt in a keyboard-based program or SIGALRM in a signal-based program. In such cases, the sleep() function returns immediately and the remaining sleep time is lost.


Here’s an example of how to use it:

import time

print("Start of program")
print("End of program")

In this example, the program will print “Start of program” and then pause for 5 seconds before printing “End of program”.

Here’s a more advanced example that demonstrates the use of sleep() in a loop:

import time

for i in range(5):
    print("Iteration", i)

In this example, the program will print “Iteration 0”, pause for 1 second, print “Iteration 1”, pause for another second, and so on, until the loop finishes after 5 iterations.