How to print something only every n iterations in python ?

Published: December 16, 2020

Tags: Python;

DMCA.com Protection Status

To print something only every n iterations in python, a solution is to use a modulo operation (or operator % in python).

For example let's print the variable i in a loop for only after every 10 iterations:

for i in range(100):
    if i % 10 == 0: 
        print('i = {}'.format(i))

returns here

i = 0
i = 10
i = 20
i = 30
i = 40
i = 50
i = 60
i = 70
i = 80
i = 90
for i in range(100):
    if i % 25 == 0: 
        print('i = {}'.format(i))

returns

i = 0
i = 25
i = 50
i = 75