Reputation: 51
How to start a loop from certain number to n numbers in python.
Example: starting loop from 2 but ending based on n numbers If I start a loop from 2 but wish to go through next 5 numbers how to achieve that?
2 3 4 5 6 7
Upvotes: 3
Views: 6536
Reputation: 4241
Range will do that for you
start = 2
length = 6
for i in range(start, start + length):
print(i)
Or you could get a range from 0 and add your offset onto the number inside the loop
for i in range(length):
print(i+start)
Which would be less common but depending on the scenario this might be more readable.
Upvotes: 4