Python sleep() Function


Python sleep()

Python time library provides sleep() function that suspends the execution of current program for specified number of seconds.


Syntax

The syntax of time.sleep() function is

time.sleep(seconds)

where seconds is a floating point value.

Import time library before using the sleep() function in the program.


Example

In the following program, we read a number (float value) from user, and make the program sleep that many seconds.

To understand that the program is pausing for that many seconds, we shall print the time before and after the sleep() statement.

Python Program

import time

n = float(input('Enter number of seconds : '))

print(time.asctime())
print('Waiting ', n, 'seconds...')
time.sleep(n)
print(time.asctime())

Output #1

Enter number of seconds : 4
Thu Feb 17 20:24:10 2022
Waiting  4.0 seconds...
Thu Feb 17 20:24:14 2022

Output #2

Enter number of seconds : 1.5
Thu Feb 17 20:24:53 2022
Waiting  1.5 seconds...
Thu Feb 17 20:24:55 2022

Conclusion

In this tutorial, we learned what sleep() function is, and how to use this function to suspend the execution of the program for a specific duration in time.


Python Libraries