Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to do conditionals inside Python (3) for loops?

Coming from primarily coding in Java and wanted to know if Python could use conditionals and different kinds of incrementing inside its for loops like Java and C can. Sorry if this seems like a simple question.

i.e.:

boolean flag = True
for(int i = 1; i < 20 && flag; i *= 2) {
    //Code in here
}
like image 524
GrainsAndRice Avatar asked Jul 01 '20 18:07

GrainsAndRice


People also ask

Can we give condition in for loop in Python?

In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated by a break statement.

Can we have conditional statements within a loop?

Every procedural programming language has conditional statements (if-statements) and iterative statements (loops). You should be familiar with the concepts —unless your only previous programming language was a purely functional language.


4 Answers

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
    
like image 67
chepner Avatar answered Oct 14 '22 05:10

chepner


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.

like image 32
Mike Organek Avatar answered Oct 14 '22 06:10

Mike Organek


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 !

like image 2
Abhishek Bhagate Avatar answered Oct 14 '22 06:10

Abhishek Bhagate


In a sense, but it's not quite as simple as it is with JS and Java.

Here is your example written in Python using a while loop with two conditions. Also note that in Python while loops, you cannot assign or increment the index in the loop's declaration.

boolean_flag = True

i = 1
while (i < 20 and boolean_flag):
    i *= 2
    # Code in here
like image 1
Gabe Avatar answered Oct 14 '22 06:10

Gabe