The Python time sleep() method suspends execution for a certain time limit. However, this method only halts the execution of a specific thread; and not the entire program.
The argument accepted by this method may be a floating point number to indicate a more precise sleep time.
The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal’s catching routine.
Syntax
Following is the syntax for sleep() method −
time.sleep(t)
Parameters
t − This is the number of seconds execution to be suspended.
Return Value
This method does not return any value. It just halts the program execution for the given time.
Example
The following example shows the usage of the Python time sleep() method.
import time
print("Start:", time.ctime())
time.sleep(5)
print("End:", time.ctime())
When we run above program, it produces following result −
Start: Tue Jan 10 09:48:49 2023
End: Tue Jan 10 09:48:54 2023
Example
Now let us see how this method works in a for loop.
In the example below, we are printing a range of numbers using the for loop and halting the execution for each iteration using the sleep() method.
import time
print("Start program")
for x in range (0, 5):
print(x)
time.sleep(2)
print("Program halted for 2 seconds")
print("End Program")
Once compiled and run, the program prints the numbers after sleeping for 2 seconds each −
Start program
0
Program halted for 2 seconds
1
Program halted for 2 seconds
2
Program halted for 2 seconds
3
Program halted for 2 seconds
4
Program halted for 2 seconds
End Program
Example
This method can also take fractional values as an argument. The program demonstrating it is given below.
import time
print("Start:", time.ctime())
time.sleep(0.5)
print("End:", time.ctime())
If we compile and run the given program, the output is displayed as follows where each print statement is executed with a 0.5 seconds gap −
Start: Wed Jan 11 14:20:27 2023 End: Wed Jan 11 14:20:27 2023
Example
Let us also try to pass a fractional valued argument to the method with the loop statements as shown in the example below −
import time
print("Start program")
for x in range (0, 5):
print(x)
time.sleep(2)
print("Program halted for 2 seconds")
print("5")
time.sleep(1.5)
print("Program halted for 1.5 seconds")
print("End Program")
On executing the program above, the output is displayed as follows −
Start program
0
Program halted for 2 seconds
1
Program halted for 2 seconds
2
Program halted for 2 seconds
3
Program halted for 2 seconds
4
Program halted for 2 seconds
5
Program halted for 1.5 seconds
End Program