首页 > 解决方案 > 在“for循环”中每第三次迭代后休眠

问题描述

我试图让我的脚本在'for循环'中的每第三次迭代后休眠。这是我到目前为止所拥有的:

 #List of words
 Word_list = ['apple','orange','grape','mango','berries','banana','sugar']

 #Loop through the list of words with the index and value of the list
 for i,word in enumerate(Word_list):
     #Store value of i in v
     v = i
     #If the value of the index, same as the 3rd loop iteration is 3, do this
     if v == 3*(i+1):
       sleep(3)
       print(i+1,word,'done')
     #Else do this
     else:
       print('exception')

输出不是我所期望的。

预期输出为:

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

标签: pythonpython-3.xlistfor-loop

解决方案


这应该这样做。做v = i然后检查v == 3 * (i + 1)总是会给出 False 因为你正在检查i==3*(i+1)哪个是真的i=-1/2

import time
Word_list = ['apple','orange','grape','mango','berries','banana','sugar']
#Loop through the list of words with the index and value of the list
for i,word in enumerate(Word_list, 1):
    #modulus function checks for divisibility by 3
    if (i %3 == 0):
        time.sleep(1)
        print(i,word,'done')
    #Else do this
    else:
       print('exception')

推荐阅读