c语言延迟函数sleep_如何使用sleep()函数在Python中进行时间延迟

c语言延迟函数sleep

There are times when you want your program to run immediately. But there are also some times when you want to delay the execution of certain pieces of code.

有时您希望程序立即运行。 但是有时您也想延迟某些代码的执行。

That's where Python's time module comes in. time is part of Python's standard library, and contains the helpful sleep() function that suspends or pauses a program for a given number of seconds:

这就是Python的time模块的用武之地。 time是Python的标准库的一部分,并包含有帮助sleep()函数,暂停或暂停节目的几秒钟内给定数量:

import time

print('runs immediately')

for letter in 'hello, world!':
    time.sleep(2)  # sleep 2 seconds between each print
    print(letter)

Output:

输出:

runs immediately
h # each character printed after a two second delay
e
l
l
o
,

w
o
r
l
d
!

Floating point numbers can be given as the argument to sleep() for more precise sleep times. For example, the following code will delay each print() statement for half a second, or 500 ms:

可以将浮点数作为sleep()的参数来获得更精确的睡眠时间。 例如,以下代码将每个print()语句延迟半秒或500毫秒:

import time

for letter in 'floats work, too':
  time.sleep(0.5) # adds a 500 ms delay
  print(letter)

Output:

输出:

f # each character printed after a 500 ms delay
l
o
a
t
s

w
o
r
k
,

t
o
o

Sometimes you might need to delay for known, different increments of time. In that case you can iterate through a list of different delay periods with a for loop:

有时您可能需要延迟已知的不同时间增量。 在这种情况下,您可以使用for循环遍历不同延迟时间的列表:

import time

for i in [.5, 1, 2, 3, 4]:
  time.sleep(i)
  print(f"Delayed for {i} seconds")

Output:

输出:

Delayed for 0.5 seconds
Delayed for 1 seconds
Delayed for 2 seconds
Delayed for 3 seconds
Delayed for 4 seconds

As you can imagine, there's a lot that you can do with the sleep() function. Now go ahead and try it in your own programs – no need to sleep on it!

您可以想象, sleep()函数可以做很多事情。 现在继续尝试在您自己的程序中尝试–无需睡觉!

更多信息: (More Information:)

Time module documentation on the sleep function.

有关睡眠功能的时间模块文档

更多Python教程: (More Python tutorials:)

The best Python tutorials

最好的Python教程

The best Python code examples

最好的Python代码示例

Python for Everybody from Dr. Chuck

Chuck博士的《适合所有人的Python》

翻译自: https://www.freecodecamp.org/news/time-delay-python-sleep-function/

c语言延迟函数sleep

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值