Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 - using for loop in a if condition

I would like to do things like this with a for in a single line, can i do it or i have to use a filter?

not 0 <= n <= 255 for n in [-1, 256, 23]
# True
0 <= n <= 255 for n in [0, 255, 256]
# False
0 <= n <= 255 for n in [0, 24, 255]
# True
like image 982
rickerp Avatar asked Dec 28 '17 22:12

rickerp


People also ask

Can you put a for loop in an if statement in Python?

You can put a for loop inside an if statement using a technique called a nested control flow. This is the process of putting a control statement inside of another control statement to execute an action.

How do you combine for loop and if condition in Python?

If you want to combine a for loop with multiple conditions, then you have to use for loop with multiple if statements to check the conditions. If all the conditions are True, then the iterator is returned. Syntax: [iterator for iterator in iterable/range(sequence) if (condition1) if (condition2) .........]

Can we write for loop inside if condition?

No. The condition is evaluated ONCE when the code reaches the IF statement, and then the whole for loop would be executed without ever checking the condition again.


1 Answers

What you are looking for is all:

all(0 <= n <= 255 for n in [0, 255, 256])
# False
all(0 <= n <= 255 for n in [0, 24, 255])
# True
not all(0 <= n <= 255 for n in [-1, 256, 23])
# True
like image 188
user2390182 Avatar answered Oct 17 '22 20:10

user2390182