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

如何实现Python for循环每三次迭代后sleep?现有代码输出异常

解决Python循环每第三次迭代后执行sleep的问题

Hey Mikee, let's troubleshoot why your loop isn't behaving the way you want it to!

First, let's break down the issue in your current code:
You set v = i and then check v == 3*(i+1), but since i starts at 0 (thanks to enumerate), 3*(i+1) will always be significantly larger than i. For example, when you're on the 3rd iteration (where i=2), 3*(2+1)=9—2 will never equal 9, so your code always hits the else block and prints "exception". That's why your output isn't matching what you expected!

The Fixes

You need to check if the current iteration number (which is i+1, since enumerate starts counting from 0) is a multiple of 3. Here are two simple, working approaches:

Option 1: Check if iteration number is divisible by 3

This is the most readable approach, since it directly checks the number of the iteration:

from time import sleep  # Don't forget to import sleep—your original code missed this!

Word_list = ['apple','orange','grape','mango','berries','banana','sugar']

for i, word in enumerate(Word_list):
    iteration_num = i + 1
    if iteration_num % 3 == 0:
        sleep(3)
        print(f"{iteration_num}, {word}, done")
    else:
        print('exception')

Option 2: Check index modulo 3 equals 2

Since the 3rd iteration has an index of 2, the 6th has an index of 5, etc., we can use modulo directly on the index (no need to calculate the iteration number):

from time import sleep

Word_list = ['apple','orange','grape','mango','berries','banana','sugar']

for i, word in enumerate(Word_list):
    if i % 3 == 2:
        sleep(3)
        print(f"{i+1}, {word}, done")
    else:
        print('exception')

Expected Output

Running either of these will produce exactly the output you wanted:

exception
exception
3, grape, done
exception
exception
6, banana, done
exception

A quick reminder: Always make sure to import sleep from the time module—without that, your code would throw a NameError when trying to call sleep()!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:58:31