The time.sleep()
function suspends the execution of a script for a specified period of time. During this suspension period, no CPU time is used.
sleep(seconds)
copy
seconds |
A required argument specifying the number of seconds to delay the execution, it maybe a floating point number for subsecond precision. |
The function delays execution for the specified number of seconds. This means that the execution stops and only resumes after the specified seconds have elapsed.
Note: You cannot un-pause the time.sleep()
function before the specified seconds have elapsed.
The following example prints each word in a given sentence after half a second.
import time def word_by_word(sentence): words = sentence.split() for word in words: print(word) time.sleep(0.500) word_by_word("All animals are equal but some animals are more equal than others.")
copy
Output:
All
animals
are
equal
but
some
animals
are
more
equal
than
others.
Try running the above program to see the effect.
A Countdown timer
The following countdown() function prints the the integers starting from the number specified as the argument down to 0 with an interval of 1 second.
import time def countdown(seconds = 10): print("Started!") for i in reversed(range(seconds)): print(i) time.sleep(1) print("Done!") countdown()
copy
Output:
Started!
9
8
7
6
5
4
3
2
1
0
Done!
Run the program to see the resulting effect.