Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

    ...
like image 937
Cristian Diaconescu Avatar asked Jul 28 '10 15:07

Cristian Diaconescu


People also ask

What is the alternative for for loop in Python?

Map() Function in Python The map() function is a replacement to a for a loop. It applies a function for each element of an iterable.

Does Python have a for loop?

The for loop uses the syntax: for item in object, where “object” is the iterable over which you want to iterate. Loops allow you to repeat similar operations in your code. One of the most common types of loops in Python is the for loop. This loop executes a block of code until the loop has iterated over an object.

Why doesn't Python have normal for loops?

The answer to your question is "Because they're different languages". They're not supposed to work alike. If they worked alike, they'd be the same language.


2 Answers

Yes, this is how I would do it

>>> for i in xrange(0, 10):
...     if i == 4:
...         continue
...     print i,
...
0 1 2 3 5 6 7 8 9

EDIT
Based on the update to your original question... I would suggest you take a look at optparse

like image 96
sberry Avatar answered Oct 12 '22 02:10

sberry


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

In python would be written as

i = 0
while i < 10
   if someCondition
      i += 1
   print i
   i += 1

there you go, that is how to write a c for loop in python.

like image 20
Netzsooc Avatar answered Oct 12 '22 01:10

Netzsooc