Is there a way to do conditionals inside Python (3) for loops?
You can use range()
if you have the step as some constant increment (like i++,i+=10,etc). The syntax is -
range(start,stop,step)
range(start, stop, step)
is used as a replacement for for (int i = start; i < stop; i += step)
. It doesn't work with multiplication, but you can still use it (with break
) if you have something like i < stop && condition
.
The equivalent loop for the one you mentioned in question can be =>
for(int i=0;i<20;i*=2) // C/C++ loop
# Python - 1
i = 0
while i < 20 : # Equivalent python loop
# Code here
i*=2
If you are willing to use flag as well as a condition, you will have to do it as =>
// C/C++
bool flag = true;
for(int i=0;i<20&&flag;i*=2) // C/C++ loop
# Python - 1
i,flag = 1,True
while not flag and i < 20 : # Equivalent python loop
# Code here
i*=2
Hope this helps !
Not directly. A for
loop iterates over a pre-generated sequence, rather than generating the sequence itself. The naive translation would probably look something like
flag = True
i = 1
while i < 20:
if not flag:
break
...
if some_condition:
flag = False
i *= 2
However, your code probably could execute the break
statement wherever you set flag
to False
, so you could probably get rid of the flag altogether.
i = 1
while i < 20:
...
if some_condition:
break
i *= 2
Finally, you can define your own generator to iterate over
def powers_of_two():
i = 1
while True:
yield i
i *= 2
for i in powers_of_two():
...
if some_condition:
break
The for
loops in Python are not like loops in C. They are like the for-each loops applied to iterables that came out in Java 7:
for (String name: TreeSet<String>(nameList) ) {
//Your code here
}
If you want control over your iterator variable, then a while
or for
loop with a break
in it is probably the cleanest way to achieve that kind of control.
This might be a good time to look into finding time to do a tutorial on Python comprehensions. Even though they are not directly applicable to your question, that is the feature that I appreciate most having come from Java about five years ago.