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.
3 Answers 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
4 Comments
range (4, 10))? I do appreciate your help.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
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)
print(i, i + 15 + i // 3)- is this what you are looking for? Noifs needed