Mikee
Mikee

Reputation: 854

Sleep after every third iteration in the 'for loop'

I'm trying to make my script sleep after every third iteration in the 'for loop'. This is what I have so far:

 #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')

The output is not what I expected though.

Expected output is:

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

Upvotes: 0

Views: 386

Answers (3)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20500

This should do it. Doing v = i and then checking v == 3 * (i + 1) will always gives False since you are checking i==3*(i+1) which is true for 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')

Upvotes: 1

hiro protagonist
hiro protagonist

Reputation: 46899

this is a variant:

from time import sleep

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, start=1):
    if i % 3 == 0:
        sleep(3)
        print(i, word, 'done')
    else:
        print('exception')

the trick is to start the enumeration at 1 and check if i%3 is zero.

Upvotes: 0

Matthew Barlowe
Matthew Barlowe

Reputation: 2328

Your condidtion of your if statement isn't doing what you want it to do. v will never equal 3*(i+1) because you set i=v earlier in the loop. What you want to do is the modulus of v by 3 where it will be equal to 0 that way you know it has been three times looping through the list. This is what the code should look like

import time
#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 + 1) %3 == 0:
        time.sleep(3)
        print(i+1,word,'done')
    #Else do this
    else:
        print('exception')

which gives this output:

exception
exception
3 grape done
exception
exception
6 banana done
exception

Upvotes: 0

Related Questions