0

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.

0

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

In the if statement, I had to change i to (i+1) since I don't want to increase the variable in the beginning, when i = 0. Or I could have decreased the value of var by increment in the beginning. But aside from that it works, thank you
Good point, that's a solution. Other answer suggests including a supplementary boolean if the if, for instance if i or if i > 0 could play the trick to avoid the first increase.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.