0

I am looking for an output in the following manner: If my inputs are

starting_value = 8
ending_value = 20

I want output as

8 13    ##8+(5) = 13
14 19   ##start of next iteration should be 13+1 = 14, and then 14+(5)

I wrote a for loop for this:

for i in range(8,20):
    start = i
    end = i+5
    print(start,end)
    i = end+1

But I'm getting wrong result:

8 13
9 14
10 15
11 16
12 17
13 18
14 19
15 20
16 21
17 22
18 23
19 24

Is there something wrong in my for loop, Any better pythonic way to do this?

1
  • 2
    The reason why your for-loop doesn't work, is because i takes a new value from the range(8, 20) iterator on each iteration. The statement i = end + 1 doesn't do anything. for in python is a for-each loop & not a traditional C for-loop. Commented Aug 20, 2019 at 9:01

4 Answers 4

3

You can do that by using a step size of 6 in your range:

starting_value = 8
ending_value = 20
step = 5

for i in range(starting_value, ending_value, step + 1):
    start = i
    end = i + step
    print(start,end)

Output:

8 13
14 19
Sign up to request clarification or add additional context in comments.

Comments

1

Simple shifting:

for i in range(8, 20, 6):
    print(i, i+5)

The output:

8 13
14 19

The same with predefined variables:

start, end, step = 8, 20, 5

for i in range(start, end, step+1):
    print(i, i + step)

Comments

0

try this:

i = 8
while i <20:
    start = i
    end = i+5
    print(start,end)
    i = end+1

output:

8 13
14 19

Comments

0

Here is my take on it:

starting_value = 8
ending_value = 20

start = starting_value
end = starting_value
while end+1 < ending_value:
  end = start + 5
  print(start, end)
  start = end + 1

Output:

8 13
14 19

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.