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.

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.

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 the randomness comes into play.

Waiting for 2, 4, 6 seconds

Let’s modify the last part of code, and make the program display the counter every 2, 4, 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.

Set a range of time 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:

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: