How To Wait 5 Seconds In Python

Sometimes, you may need to pause the execution of your Python script for a specific duration, such as 5 seconds. In this blog post, we will learn how to make your Python script wait for 5 seconds using the time.sleep() function in the time module.

Using the time.sleep() Function

The time module provides a function called time.sleep(), which allows you to pause the execution of your script for a specified number of seconds. To use the time.sleep() function, you need to import the time module and then call the function with the desired wait time (in seconds) as its argument.

Here’s an example to demonstrate how to use the time.sleep() function to pause your script for 5 seconds:

    import time
    
    print("Starting script...")
    time.sleep(5)
    print("...Script resumed after 5 seconds")
    

In this example, the script will print “Starting script…”, then wait for 5 seconds before printing “…Script resumed after 5 seconds”. The time.sleep(5) function call is what makes the script wait for 5 seconds.

Example: Running a Loop with 5-Second Intervals

Let’s say you want to run a loop that executes a specific action every 5 seconds. You can use the time.sleep() function to pause the loop for 5 seconds between each iteration. Here’s an example:

    import time

    for i in range(3):
        print(f"Loop iteration {i+1}")
        print("Performing some action...")
        time.sleep(5)
    

In this example, the script will run a loop 3 times, printing “Loop iteration X” and “Performing some action…” in each iteration. The time.sleep(5) function call inside the loop causes the script to pause for 5 seconds between each iteration.

Conclusion

The time.sleep() function is a useful and straightforward way to pause your Python script for a specific duration, such as 5 seconds. By simply importing the time module and calling time.sleep() with the desired wait time as an argument, you can easily implement waiting times in your script, whether it’s for running loops with intervals or pausing a script’s execution.