sleep() is defined in time() module of python 3. Sometimes, there is a need to hault 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.
Syntax : sleep(sec)
sec : Number of seconds for which the code is required to be stopped.
Returns : VOID.
Code #1 : Demonstrating 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 it execution of the background thread which is repeated at regular interval, this can be implemented with the help of sleep(). Another popular application is using sleep() to print the words letter by letter for good user interface. The latter is represented from this code below.
Code #2 : Demonstrating application of sleep()
Note : Visible effect of sleep() can be seen in the local editor.
Code #3: Creating Time Delay in List
After the delay of 5 seconds, we will get the output as:
['Jai', 'Shree', 'RAM', 5, 'August', 2020]
Code #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')
Code #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:
Code #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
Code #7: Creating a Time Delay of 3 minutes in List
After the delay of 3 minutes, the list will be displayed as:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course