How to add time delay in Python?

Published on Aug. 22, 2023, 12:15 p.m.

To add a time delay in Python , you can use the built-in time module, which provides a sleep() function that can pause the execution of your program for a specified number of seconds. Here’s an example:

import time

# Delay program execution for 5 seconds
time.sleep(5)

# Continue program execution after delay
print("Hello, World!")

In this example, we import the time module and call its sleep() function to pause the execution of our program for 5 seconds. After the delay, we print a message to the console.

You may also specify a fractional number of seconds to sleep() function. For example, time.sleep(0.5) will pause the execution of your program for half a second.

To add a time delay within a loop in Python

To add a time delay within a loop in Python , you can use the time module’s sleep() function within the loop’s body. Here’s an example:

import time

# Loop 5 times with a 1-second delay between iterations
for i in range(5):
    print("Iteration", i)
    time.sleep(1)

In this example, we use a for loop to iterate 5 times, printing a message to the console and pausing for a 1-second delay between each iteration using the time.sleep() function.

You can set the duration of your delay to any value in seconds, whether that is a whole number or a fraction. For example, time.sleep(0.5) would delay for half a second.

Tags: