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
...
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With