Iterative Modulo Application

Hello!

I recently finished the modulo lesson in the intro python course. In it, it is mentioned that
“The modulo operator is useful in programming when we want to perform an action every nth-time the code is run”

Could anyone please explain to me why and how this might work?

Thanks!

Say you want to perform j+5 every time the number is run 2 times (or the iteration number is a multiple of two). You could do:

for i in range(100000):#just a big number for example
  if i%2 == 0:
    j+=5

Here, we’re using the modulo to check if the iteration is a multiple of 5. It’s quite a silly example, though.

1 Like

Hey! Thanks for following up on my question!

I think I am interpreting your example - although I am stuck on where j comes into the picture. Is j just a variable defined elsewhere in the function? How does j+=5 check if the iteration is a multiple of 5?

Yes, j should have been defined outside of the for loop:

j = 0
for i in range(100000):#just a big number for example
  if i%2 == 0:
    j+=5

I see! Thanks for clarifying :wink:

1 Like