PretendNotToSuck
PretendNotToSuck

Reputation: 404

Python: Change variable depending on for loop iteration

I have a for loop with a 100 iterations and I would like to change the value of a variable for every 10 iterations. One way of doing this would be:

for i in range(100):

    if i < 10:
        var = 1
    elif i < 20 :
        var = 1.5
    ... 

But I don't want to have 10 if statements. Is there a better way of doing it? In this case, the variable changes by the same amount for every 10 iterations.

Upvotes: 0

Views: 713

Answers (2)

Petr Blahos
Petr Blahos

Reputation: 2433

There is this modulo operator %

for i in range(100):
    if 0 == i % 10:
        var = var + 0.5

or if you want to change var on other than the first iteration:

for i in range(100):
    if i and 0 == i % 10:
        var = var + 0.5

Upvotes: 1

arnaud
arnaud

Reputation: 3473

You're looking for the modulo (%) operator. From the docs:

The % (modulo) operator yields the remainder from the division of the first argument by the second.

Indeed, 11 = 10 * 1 + 1 hence 11 % 10 = 1, but 30 = 10*3 + 0 hence 30 % 10 = 0! And you're looking for all those that are a factor of ten:

increment = 0.5
for i in range(100):
    if i % 10 == 0:
        var += increment

Upvotes: 2

Related Questions