Wait Using the time.sleep() Function in Python

The time.sleep() function takes a float value (which represents the number of seconds) as an argument and causes a program to wait for a given number of seconds. After that time the next part of the code is going to be executed.

The following code causes a program to wait for 1.5 seconds.

Simple wait

Let’s see how the sleep function works in practice.

This program will display “Hello”, and after 3 seconds it will display the next part of the message.

Hello!
I waited 3 seconds to display this message.

Wait in a loop

The practical application of this function can be found in loops. You can use the while loop to display a message every n seconds.

This code displays the message every 3 seconds and displays it to the output until you stop it, or the program crashes, etc.

Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5

Adding randomness

Forcing a program to wait is very important in scraping. When you don’t want to be blocked or overload the server, you can use the wait function. But waiting for the n number of seconds each time is easily detectable, so randomness comes into play.

Waiting for 2, 4, or 6 seconds

Let’s modify the last part of the code, and make the program display the counter every 2, 4, and 6 seconds. Before we do that, we have to import the random module. It’s responsible for generating pseudo-random numbers.

The program will wait every 2, 4, or 6 seconds.

I waited 2 seconds to display this message.
I waited 6 seconds to display this message.
I waited 4 seconds to display this message.

Set a range of times to wait

To set the minimum and maximum time to wait, we can use the randint function. The program will generate a random int between two ranges. In our case 1 and 10 seconds.

The result of the program:

I waited 8 seconds to display this message.
I waited 1 seconds to display this message.
I waited 10 seconds to display this message.

Check how much time you waited

So far we set a time to wait. Let’s see how much time we had to wait for Python to finish the program. Let’s see how much we have to wait for the program to generate the Fibonacci sequence for different numbers.

On my computer, the program generated these responses:

Fib(20): 0.0020 sec
Fib(25): 0.0290 sec
Fib(30): 0.3140 sec
Fib(35): 3.4409 sec
Fib(40): 44.7275 sec