Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate multiple variables in one 'if' statement?

Say I have a bunch of variables that are either True or False. I want to evaluate a set of these variables in one if statement to see if they are all False like so:

if var1, var2, var3, var4 == False:
    # do stuff

Except that doesn't work. I know I can do this:

if var1 == False and var2 == False and var3 == False and var4 == False:
    # do stuff

But that's fairly ugly - especially if these if statements are going to occur a lot in my code. Is there any sort of way I can do this evaluation with a cleaner syntax (like the first example)?

like image 682
Rauffle Avatar asked Feb 29 '12 18:02

Rauffle


People also ask

How do you compare multiple values in an if statement?

To check if a variable is equal to all of multiple values, use the logical AND (&&) operator to chain multiple equality comparisons. If all comparisons return true , all values are equal to the variable. Copied! We used the logical AND (&&) operator to chain multiple equality checks.

Can you have multiple conditions in an if statement?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

How do you compare two variables in IF statements in Python?

You can compare 2 variables in an if statement using the == operator.

Can you have multiple conditions in an if statement Python?

Python supports multiple independent conditions in the same if block. Say you want to test for one condition first, but if that one isn't true, there's another one that you want to test. Then, if neither is true, you want the program to do something else. There's no good way to do that using just if and else .


2 Answers

You should never test a boolean variable with == True (or == False). Instead, either write:

if not (var1 or var2 or var3 or var4):

or use any (and in related problems its cousin all):

if not any((var1, var2, var3, var4)):

or use Python's transitive comparisons:

if var1 == var2 == var3 == var4 == False:
like image 144
phihag Avatar answered Oct 20 '22 00:10

phihag


How about this:

# if all are False
if not any([var1, var2, var3, var4]):
    # do stuff

or:

# if all are True
if all([var1, var2, var3, var4]):
    # do stuff

These are easy to read, since they are in plain English.

like image 29
Steven T. Snyder Avatar answered Oct 20 '22 00:10

Steven T. Snyder