0

I want to do a for loop and explain it here by simple print function. I want change the data printed after a fixed value. Let's regard this code:

for i in range (7):
    print (i, i+15, i+1)

it gives me:

0 15 1
1 16 2
2 17 3
3 18 4
4 19 5
5 20 6
6 21 7

But I want to add 1 to the printed values of the second row after each 3 interation. I mean from the first to third iteration, I want the same results as printed above. But from third to sixth I want to add 1 to i+15 (printing i+16 rather than i+15). Then again after the sixth row, I want to add 1 to i+16 (printing i+17 rather than i+16 or i+15). I mean I want to have this one:

0 15 1
1 16 2
2 17 3
3 19 4
4 20 5
5 21 6
6 23 7

How can I make my i in the function to e such a thing? Itried the following but it gives another thing:

for i in range (7):
    if i % 3 == 0:
        print (i, i+15+1, i+1)
    else:
        print (i, i+15, i+1)

I do appreciate any help in advance.

1
  • 1
    print(i, i + 15 + i // 3) - is this what you are looking for? No ifs needed Commented Dec 3, 2020 at 11:55

3 Answers 3

3

Try this:

for i in range (7):
    print (i, i//3+i+15, i+1)

0 15 1
1 16 2
2 17 3
3 19 4
4 20 5
5 21 6
6 23 7

For ranges that don't start from 0, to keep the same logic (increment every 3 iterations) you can do the following:

for i in range (4,15):
        print (i, (i-4)//3+i+15, i+1)

4 19 5
5 20 6
6 21 7
7 23 8
8 24 9
9 25 10
10 27 11
11 28 12
12 29 13
13 31 14
14 32 15
Sign up to request clarification or add additional context in comments.

4 Comments

Dear @IoaTzimas Thanks for you helpful solution. I tried to do it for ranges which does not start from 0, but it does not work out for them. Can you please tell me how I can extend your solution to other ranges (for example range (4, 10))? I do appreciate your help.
Sure, do you want to always keep groups of 3, no matter the start of the range?
Yes, exactly. My steps are 3 but start is from 4 up tp 10 (for example). Thanks in advance.
Code updated. Just add (i-k)//3 where k is the start of the range
2
print("Hello world")
starting = 14;
for i in range (7):
    
    if(i %3==0):
        starting=starting+1
    print (i, i+starting, i+1)

Just added if condition to detect

Comments

1

You can do smth like this:

for i in range(7):
    print(i, i + 15 + i // 3, i + 1)

or, if you want, you can save this delta to variable.

inc = 0
for i in range(7):
    if i > 0 and i % 3 == 0:
        inc += 1
    print(i, i + 15 + inc, i + 1)

I think more pythonic way of 2nd variant:

inc = 0
for i in range(7):
    if i > 0:
        inc += i % 3 == 0
    print(i, i + 15 + inc, i + 1)

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.