You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python中的While循环设置延迟?

解决Python循环放慢与无限循环问题

一、让循环放慢速度

要让循环每次执行后暂停1-2秒,直接用Python内置的time模块的sleep()函数即可,步骤如下:

  1. 导入time模块(如果需要随机等待时长,再导入random模块)
  2. 在print("test")之后调用sleep()传入等待秒数

固定等待时长示例(比如1.5秒):

import time

def cursor():
    global cursors
    cursors += 1
    while True:  # 用while True比1==1更符合Python规范
        print("test")
        time.sleep(1.5)  # 暂停1.5秒后再执行下一次循环

随机1-2秒等待示例:

如果想每次等待时长在1到2秒之间随机变化,可以结合random.uniform():

import time
import random

def cursor():
    global cursors
    cursors += 1
    while True:
        print("test")
        wait_time = random.uniform(1, 2)  # 生成1~2之间的随机浮点数
        time.sleep(wait_time)

二、用for循环实现无限运行

如果一定要用for循环做无限循环,可以借助itertools模块的count()函数,它会生成一个无限递增的整数序列,示例:

import time
import itertools

def cursor():
    global cursors
    cursors += 1
    # itertools.count()会不断生成0,1,2,...无限循环下去
    for _ in itertools.count():
        print("test")
        time.sleep(1.5)

不过要说明的是,while True是Python中实现无限循环最简洁直观的方式,日常开发中更推荐使用这种写法。

内容的提问来源于stack exchange,提问作者Bluffyyy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 09:24:16