1

I have programmed in C++ earlier but I am new to Python. I searched for this but i was not able to find the appropriate answer. In C++, I can do:

for(int i=0; i<10;i++)
{
   i+=5;
   std::cout<<i<<std::endl
}

The values of i would be 5 and 11. But in python if i do:

for i in range(0,10):
   i+=5
   print i

The value of i does update for that iteration of loop, but in the next iteration, it will become 1. While I do understand that in python, after each iteration, i will contain the next value in the tuple/list generated by range, but is there any way I can make it skip iterations like in C++? I really don`t want to use the next() function 5 times

EDIT: I can use the third parameter of range function for general use, but what if I want to skip some iterations for say if only a certain condition is true. eg

for(int i=0; i<10;i++)
{
   if(i%2)i+=1;
   std::cout<<i<<std::endl
}
2
  • 3
    you might want to use range third parameter which specify the step size. If that doesn't suit you, consider a regular while loop. Commented Jul 2, 2016 at 19:35
  • 1
    The best way to do this in Python will depend on why you want to skip 5 iterations. You wouldn't really write code like your C++ example. Sometimes toy simplifications obscure the real topic. Commented Jul 2, 2016 at 19:37

3 Answers 3

6

If you want to skip iterations when a condition is true, then use continue:

for i in range(10):
    if i % 2:
        continue
    print(i)
Sign up to request clarification or add additional context in comments.

2 Comments

The question is not really about using continue as a solution. It's about altering the loop iteration based on an if condition. if (someCondition) {change the value of i to something else}
@Nav the question says, "what if I want to skip some iterations"
6

You can use a regular while loop. it will look less nice but it does the job. for example:

i = 0
while i < 100:
    print i
    if i % 2 == 0:
        i += 5
    i+=1

Comments

5

I know what you were thinking, but there's something built-in for python that allows you to set the iteration step within the range() function. Here is the official Python Documentation on range().

In essence, to skip x after each iteration, you would do:

for i in range(start, stop, x + 1):
    # functions and stuff

Hope this helped.

2 Comments

But, it ain't generic. It'll work only when you have a constant skip. What if you have to skip multiples of 3 as well as 2?
@hashcode55 That's the drawback for using the built-in. See Ned Batchelder's solution for a case-sensitive way of solving the problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.