On this tutorial you’ll discover ways to use the sleep() operate of Python’s built-in time module so as to add time delays to code.
Once you run a easy Python program, the code execution takes place sequentially—one assertion after one other—with out any delay. Nevertheless, in some instances it might be essential to defer code execution. The sleep()
operate of Python’s built-in time module will assist you to with this.
On this tutorial, you’ll be taught the syntax of utilizing the sleep()
operate in Python and a number of other examples to grasp the way it works. Let’s begin!
Python syntax time.sleep()
The time
module, constructed into Python’s commonplace library, gives a number of helpful time-related capabilities. As step one, import it time
module in your working surroundings:
import time
Just like the sleep()
operate is a part of the time
module, now you can open and use it with the next normal syntax:
time.sleep(n)
Right here, n
is the quantity seconds to sleep. It may be an integer or a floating level quantity.
Typically the required delay generally is a few milliseconds. In these instances, you may convert the period in milliseconds to seconds and use it when invoking the sleep operate. For instance, if you wish to enter a delay of 100 milliseconds, you may enter it as 0.1 second: time.sleep(0.1)
.
▶ You may also choose solely the sleep
operate from the time
module:
from time import sleep
If you happen to use the above methodology for importing, you may then obtain the sleep()
operate instantly – with out utilizing time.sleep()
.
Now that you have discovered Python syntax sleep()
operate, let’s code examples to see the operate in motion. You may obtain the Python scripts used on this tutorial from the Python-sleep folder on this GitHub repository. 👩🏽💻
Gradual code execution with sleep()
As a primary instance, let’s use the sleep operate to decelerate the execution of a easy Python program.
Within the following code snippet:
- The primary
print()
assertion is executed with none delay. - Then we introduce a 5 second delay utilizing the
sleep()
operate. - The second
print()
assertion is just not executed till the sleep operation is accomplished.
# /python-sleep/simple_example.py
import time
print("Print now")
time.sleep(5)
print("Print after sleeping for five seconds")
Now enter the simple_example.py
file and examine the output:
$ python3 simple_example.py
Add completely different delays to a block of code
Within the earlier instance, we launched a set delay of 5 seconds between the execution of two print()
explanations. Subsequent, let’s code one other instance to introduce completely different delay occasions when going via an iterable.
On this instance we wish to do the next:
- Stroll via a sentence, open every phrase and print it.
- After printing every phrase, we wish to wait a sure period of time earlier than printing the subsequent phrase within the sentence.
Stroll via a collection of strings
Consider the string sentence
. It’s a string the place every phrase is a string in itself.
Looping via the string, we get every character, as proven:
>>> sentence = "How lengthy will this take?"
>>> for char in sentence:
... print(char)
# Output (truncated for readability)
H
o
w
.
.
.
t
a
okay
e
?
However this isn’t what we wish. We wish to undergo the sentence and have a look at every phrase. For this we will name the cut up()
methodology on the sentence
string. This returns an inventory of strings obtained by splitting the sentence
string-on all keep away from white house.
>>> sentence.cut up()
['How', 'long', 'will', 'this', 'take?']
>>> for phrase in sentence.cut up():
... print(phrase)
# Output
How
lengthy
will
this
take?
Loop via iterables with completely different delays
Let’s take a look at the instance once more:
sentence
is the string we wish to loop via to entry every phrase.delay_times
is the checklist of delay occasions that we are going to use as an argument for thesleep()
operate throughout every go via the loop.
Right here we wish to undergo two lists on the similar time: the delay_times
checklist and the checklist of strings obtained by splitting the sentence
string. You should use the zip()
operate to carry out this parallel iteration.
The Python zip() operate: zip(list1, list2) returns an iterator of tuples, the place every tuple incorporates the merchandise at index i in list1 and list2.
# /python-sleep/delay_times.py
import time
sleep_times = [3,4,1.5,2,0.75]
sentence = "How lengthy will this take?"
for sleep_time,phrase in zip(sleep_times,sentence.cut up()):
print(phrase)
time.sleep(sleep_time)
With out the sleep operate, the management would instantly proceed to the subsequent iteration. As a result of we launched a delay, the subsequent go via the loop solely happens after the sleep operation is accomplished.
Run now delay_times.py
and observe the output:
$ python3 delay_times.py
The next phrases within the string are printed with a delay. The delay after printing the phrase at index i
within the string the quantity is at index i
within the delay_times
checklist.
Countdown Timer in Python
As the next instance, let’s code a easy countdown timer in Python.
Let’s outline a operate countDown()
:
# /python-sleep/countdown.py
import time
def countDown(n):
for i in vary(n,-1,-1):
if i==0:
print("Able to go!")
else:
print(i)
time.sleep(1)
Subsequent, let’s outline the countDown()
operate:
- The operate takes in a quantity
n
as an argument and counts down from that quantity to zeron
. - We use time.sleep(1) to attain a one second delay between counts.
- When the depend reaches 0, the operate “Able to go!” off.
🎯 To appreciate the countdown operation, we’ve the
vary()
operate with a unfavorable step worth of -1.vary(n, -1, -1)
will assist us work via the vary of numbers in n, n – 1, n – 2, and so forth all the way down to zero. Notice that the endpoint is excluded by default when utilizing thevary()
operate.
Subsequent, let’s add a name to the countDown()
operate with 5 as an argument.
countDown(5)
Now run the script countdown.py
and see the countDown
characteristic in motion!
$ python3 countdown.py
Sleep operate with multithreading
The Python threading module gives out-of-the-box multithreading capabilities. In Python, the World Interpreter Lock or GIL ensures that just one lively thread is working at any given time.
Nevertheless, throughout I/O and wait operations reminiscent of sleep, the processor might droop the present thread and swap to a different thread that’s ready.
Let’s take an instance to grasp how this works.
Create and run threads in Python
Think about the next capabilities, func1()
, func2()
And func3()
. They undergo a sequence of numbers and print it. That is adopted by a sleep operation – for a selected variety of seconds – throughout every go via the loop. We used completely different delay occasions for every of the capabilities to higher perceive how execution switches between threads concurrently.
import time
def func1():
for i in vary(5):
print(f"Working t1, print {i}.")
time.sleep(2)
def func2():
for i in vary(5):
print(f"Working t2, print {i}.")
time.sleep(1)
def func3():
for i in vary(4):
print(f"Working t3, print {i}.")
time.sleep(0.5)
In Python you should utilize the Thread()
constructor to instantiate a thread object. Utilizing the syntax threading.Thread(goal = …, args = …)
creates a thread that the goal
operate with the argument specified within the args
tuple.
On this instance, the capabilities func1
, func2
And func3
, don’t settle for arguments. It’s due to this fact enough to specify solely the identify of the operate because the goal. Subsequent we outline wire objects, t1
, t2
And t3
of func1
, func2
And func3
because the aims, respectively.
t1 = threading.Thread(goal=func1)
t2 = threading.Thread(goal=func2)
t3 = threading.Thread(goal=func3)
t1.begin()
t2.begin()
t3.begin()
Here is the complete code for the thread instance:
# /python-sleep/threads.py
import time
import threading
def func1():
for i in vary(5):
print(f"Working t1, print {i}.")
time.sleep(2)
def func2():
for i in vary(5):
print(f"Working t2, print {i}.")
time.sleep(1)
def func3():
for i in vary(4):
print(f"Working t3, print {i}.")
time.sleep(0.5)
t1 = threading.Thread(goal=func1)
t2 = threading.Thread(goal=func2)
t3 = threading.Thread(goal=func3)
t1.begin()
t2.begin()
t3.begin()
Observe the output. The execution modifications between the three threads. The wire t3
has the bottom ready time and is due to this fact suspended for the least period of time. Wire t1
has the longest sleep period of two seconds, so it’s the final thread to finish execution.
For extra data, learn the tutorial on the fundamentals of multithreading in Python.
Conclusion
On this tutorial you discovered the right way to use Pythons sleep()
operate so as to add time delays to code.
You’ve got entry to the sleep()
operate of the built-in time module, time.sleep()
. Use to delay execution by n seconds time.sleep(n)
. You’ve got additionally seen examples of slowing down subsequent iterations in a loop with completely different values, countdowns, and multithreading.
Now you can discover the extra superior options of the time module. Wish to work with dates and occasions in Python? Along with the time module, you should utilize the performance of the datetime and calendar modules.
Subsequent, discover ways to calculate the time distinction in Python.⏰