Python: is there a C-like for loop available?

Viewed 28701

Can I do something like this in Python?

for (i = 0; i < 10; i++):
  if someCondition:
     i+=1
  print i

I need to be able to skip some values based on a condition

EDIT: All the solutions so far suggest pruning the initial range in one way or another, based on an already known condition. This is not useful for me, so let me explain what I want to do.

I want to manually (i.e. no getopt) parse some cmd line args, where each 'keyword' has a certain number of parameters, something like this:

for i in range(0,len(argv)):
    arg = argv[i]
    if arg == '--flag1':
       opt1 = argv[i+1]
       i+=1
       continue
    if arg == '--anotherFlag':
       optX = argv[i+1]
       optY = argv[i+2]
       optZ = argv[i+3]
       i+=3
       continue

    ...
12 Answers

You can ensure that an index is incremented within a try...finally block. This solve the common problem of wanting to continue to the next index without having to copy/past i += 1 everywhere. Which is one of the main advantages the C-like for loop offers.

The main disadvantage to using a try...finally is having to indent your code once more. but if you have a while loop with many continue conditions its probably worth it.

Example

This example demonstrates that i still gets incremented in the finally block, even with continue being called. If i is not incremented its value will remain even forever, and the while loop will become infinite.

i = 0
while i < 10:
    try:
        print(i)

        if i % 2 == 0:
            continue

    finally:
        i += 1

without it you would have to increment i just before calling continue.

i = 0
while i < 10:
    print(i)

    if i % 2 == 0:
        i += 1 # duplicate code
        continue

    i += 1
Related