Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python run code every 100th loop item

Tags:

python

I have this simple loop in Python that I am using..

for i, numbercode in enumerate(numbercode_list):
    print ("Item : %s" %i )
    driver.close()
    driver = init_driver()

How would I go about just running the last two lines every 100th loop item? Currently it runs them every time.

like image 634
fightstarr20 Avatar asked Apr 08 '16 13:04

fightstarr20


People also ask

How do you run a function in python every 5 seconds?

The time module sleep() function allows you to sleep your code for a defined period of time in seconds. To run code every 5 seconds in Python, you can use a loop and pass '5' for 5 seconds to sleep().

How many times loop will be executed in Python?

So it will iterate for 10 times.


1 Answers

You can take the modulus of the number and compare to zero. Modulo (% in Python) yields the remainder from the division of the first argument by the second, e.g.

>>> 101 % 100
1

>>> 100 % 100
0

For your example, this could be applied as follows:

for i, numbercode in enumerate(numbercode_list):
    print ("Item : %s" %i )
    if i % 100 == 0:
        driver.close()
        driver = init_driver()
like image 133
mfitzp Avatar answered Sep 19 '22 10:09

mfitzp