深度阅读

How to add time delay in Python?

作者
作者
2023年08月22日
更新时间
14.22 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。