time.sleep() in Python
sleep() is defined in time() module of python 3 and python 2
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 hault the flow of code for any period of time. This function discusses the insight of this function.
Syntax : sleep(sec)
Parameters :
sec : Number of seconds for which the code is required to be stopped.Returns : VOID.
Code #1 : Demonstrating sleep()
# Python code to demonstrate # working of sleep() import time # printing the start time print("The time of code execution begin is : ", end ="") print(time.ctime()) # using sleep() to hault the code execution time.sleep(6) # printing the end time print("The time of code execution end is : ", end ="") print(time.ctime()) |
Output:
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
Application :
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()
# Python code to demonstrate # application of sleep() import time # initializing string strn = "GeeksforGeeks" # printing geeksforgeeks after delay # of each character for i in range(0, len(strn)): print(strn[i], end ="") time.sleep(2) |
Output:
GeeksforGeeks
Note : Visible effect of sleep() can be seen in the local editor.
Recommended Posts:
- Reading Python File-Like Objects from C | Python
- Python | Index of Non-Zero elements in Python list
- Python | Merge Python key values to list
- Important differences between Python 2.x and Python 3.x with examples
- Python | Set 4 (Dictionary, Keywords in Python)
- Python | Add Logging to Python Libraries
- Python | Add Logging to a Python Script
- Python | Sort Python Dictionaries by Key or Value
- JavaScript vs Python : Can Python Overtop JavaScript by 2020?
- zip() in Python
- bin() in Python
- abs() in Python
- pow() in Python
- Python | a += b is not always a = a + b
- gcd() in Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



