time.sleep() in Python
Python time sleep() function suspends execution for the given number of seconds.
Sometimes, there is a need to halt the flow of the program so that several other executions can take place or simply due to the utility required. sleep() can come handy in such a situation which provides an accurate and flexible way to halt the flow of code for any period of time. This function discusses the insight of this function.
Python time sleep() syntax:
Syntax : sleep(sec)
sec : Number of seconds for which the code is required to be stopped.
Returns : VOID.
Python time sleep() method example
Example 1: Demonstrating the working of sleep()
The time of code execution begin is : Mon Apr 9 20:57:10 2018 The time of code execution end is : Mon Apr 9 20:57:16 2018
There are many applications that sleep() is used for. Be its execution of the background thread which is repeated at regular intervals, this can be implemented with the help of sleep(). Another popular application is using sleep() to print the words letter by letter for a good user interface. The latter is represented from the code below.
Example 2: Demonstrating the application of Python time.sleep(1)
Note : Visible effect of sleep() can be seen in the local editor.
Example 3: Creating Time Delay in List
After the delay of 5 seconds, we will get the output as:
['Jai', 'Shree', 'RAM', 5, 'August', 2020]
Example 4: Creating Time Delay in Tuple
After the delay of 4 seconds, we will get the output as:
('Anil Kumbl', 'Sachin Tendulkar', 'Sunil Gavaskar', 'Rahul Dravid', 'Mahendra Singh Dhoni', 'Dennis Lillee', 'Muttiah Muralitharan', 'Shane Warne')
Example 5: Creating Multiple Time Delays
After the delay of 5 seconds, the list will be displayed as:
Then after every 13 seconds, the items of the list will be displayed as:
Example 6: Time Delay in a List Comprehension
After every 7 seconds, the items of the list will be displayed as:
Anil Kumble Sachin Tendulkar Sunil Gavaskar Rahul Dravid Mahendra Singh Dhoni Dennis Lillee Muttiah Muralitharan Shane Warne
Example 7: Creating a Time Delay of 3 minutes in List
After the delay of 3 minutes, the list will be displayed as: