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)?
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.
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.
You can compare 2 variables in an if statement using the == operator.
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 .
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:
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.
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