In this article let us learn how to implement if statement in Python with multiple condition evaluation
For those of you in a hurry, here is the short version of the answer.
“if” Statement with Multiple Conditions: Short Answer
You can use the “and”/”or” logical operators in Python to implement “if” statements with multiple conditions.
x = 10 y = 5 z = 25 # usage of "and" operator if (x > y) and (y < z): print('both (x>y) and (y>z) are true') # usage of "or" operator if (x < y) or (y < z): print('either (x < y) or (y < z) is true')
This example is enough for the most of you to get back to your code and start hacking away I suppose!
But that is just the short version of the answer.
To master the concept of how ‘if’ works in python, stick around for the longer and more informative version of the answer, where we explore
- the 2 parts of the if statement,
- what are expressions and how to evaluate them,
- how to combine more than 2 conditions,
- how to combine “and”/ “or” operators to make decisions,
- how to avoid common pitfalls while implementing more than 2 conditions, and
- best practices to write “easy to read” code
with the help of several more examples!
So, let’s begin!
How “if” Statement Works in Python
Similar to C, C++, Java, and many other programming languages, in Python the if statement consists of 2 parts as shown in the illustrations below.
The 1st part is the “if” keyword and the 2nd part is the “condition” we are interested in checking.
In Python, the “condition” will evaluate to either True or False. As you might expect, if the condition evaluates to True, the statements you have inside the if clause will get executed. If the condition/expression evaluates to False then the statements inside the if clause will be skipped.
These “conditions” can be implemented using
- comparison expressions
- logical expressions, or
- functions returning Boolean values
Let us see some simple examples of Python Comparison Expressions
As you can see in the screenshot above, all comparison expressions will evaluate to the boolean values of True or False.
So coming back to the question of focus of this article, which is how to check multiple conditions in the if statement?
The answer is
We can check multiple conditions by combining the conditions into a Logical Expression, which will, in the end, boil down to a single boolean with value of either True or False
I will expand on the above lines in a bit, first let us understand what logical expressions are and how can they be implemented in Python.
Let us start with some examples.
In the code above, there are 3 boolean variables bool1, bool2, and bool3.
- bool1 is set to True,
- bool2 is set to False and
- bool3 is set to True.
The truth table for logical AND operation is shown in the table below
If you compare this truth table with the screenshot above, you can see that the and keyword in python, performs the “Logical AND” operation on an expression containing Item#1 and Item#2 and evaluates this Logical Expression to either True or False.
You can remember the Truth table for “AND Logic” very easily by keeping in your mind that both items must be True for the end result to be True, which is the same as in the English language as shown in the example below.
The code above is pretty self-explanatory, so let us move on and have a look at a simple example of how this “and” operator can be used in an “if” statement to check 2 conditions.
“if” statement with “and” to combine 2 conditions
x = True y = True if x and y: print("Both x and y are True")
“if” statement with “and” to combine 3 or more conditions
If you have 3 or more conditions, all you need to do is use another “and” operator in your code between your 2nd and 3rd condition as shown in the example below
a = 10 b = 20 c = 30 d = 40 if (a < b ) and (b < c) and (c < d): print("All 3 expressions are True")
Here the expression
- (a < b) evaluates to True since 10 is less than 20
- (b < c) also evaluates to True since 20 is less than 30
- (c < d) also evaluates to True since 30 is less than 40
Then the line 6 in Example#3 above (if statement) becomes something like the following
if True and True and True:
which then becomes
and the print statement gets executed.
What if you have more than 3 conditions? I think I won’t bore you with the details!
Python makes it very easy on us doesn’t it!
Evaluation of “and” Expressions in Python
Let us end the discussion on the “and” operator by seeing how these expressions using the “and” operator are evaluated in Python.
The below sentence is taken from python.org documentation.
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
In other words, the 2nd item will not even be evaluated if the 1st item gets evaluated to be false. If you think about it, it makes perfect sense, as for “logical AND” to evaluate to be True both item#1 and item#2 must be True. So no point wasting computing resources evaluating the 2nd expression if the 1st one has already been evaluated to False!
“if” statement with “or” to combine conditions
Let us start by looking at the truth table for logical OR operator
You can remember the Truth table for “OR Logic” very easily by keeping in your mind that at least one of the items must be True for the end result to be True, which is the same as in the English language.
Now let us take a look at a simple example to see how “logical OR” expression can be used to check multiple conditions in Python
a = 10 b = 20 c = 30 if (b > a) or (b > c): print ("atleast one of the 2 expressions evaluate to True")
Here the expression
- (b > a) evaluates to True
- (b > c) evaluates to False
Hence the line number 5 in Example#4 above becomes
if True or False:
which then becomes
and then the print statement will get executed.
I am guessing you already know how to implement “or” with more than 2 conditions (yup! just use another “or” operator to separate the 2nd and 3rd expressions!)
Evaluation of “or” expressions in Python
Let us end this discussion on the “or” operator by seeing how expressions containing the “or” operator are implemented in Python
The below sentence is taken from python.org documentation.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
In other words, the 2nd item will not even be evaluated if the 1st item gets evaluated to be True. Just like “Logical AND” implementation, this makes perfect sense, as, for “logical OR” to be True only one of the 2 items needs to be True. So no point wasting computing resources evaluating the 2nd expression if the 1st one has already been evaluated to True!
“if” statement with XOR conditions
The Truth table below shows the XOR logic
XOR logic is not part of natural English, it is something exclusive to computer science. You can remember XOR by remembering the fact that only one of the items must be True for XOR logic to be True.
Personally, I like to remember it this way: “either x or y but not both!“
If you have guessed that you can use an operator called “xor” to do this in python, you will be disappointed, as python, just like English, does not have a keyword named “xor”!
Instead, we can use the Bitwise operator for xor which is “^” the cap symbol as shown in the example below.
x = True y = False if x ^ y: print("x ^ y = ", (x ^ y))
The output of the above will look like
x ^ y = True
Bitwise operators are originally intended to be used with 2 binary values, but they work with boolean too!
But, be careful while using xor operators, make sure that the conditions in either side of “^” operator will be simplified into Boolean by Python, else you will see some weird results as shown in the example below!
x = 12 y = 20 if x ^ y: print("x ^ y = ", (x ^ y))
The output of the above code will look like
x ^ y = 24
As you can see, we got some strange number “24”, which is totally weird!
This is how python evaluated 24
- 12 is 1100 in binary
- 20 is 10100 in binary
Python used the XOR truth table and did the following math
and obtained the result 24.
Also, in Python, every non-zero integer’s boolean value is True
So line-4 in Example#6 above evaluated to be
which then became
and hence the print statement got executed!
“if” statement with NOT conditions
The “Not” logic has been covered thoroughly in a separate article given in the link below, so I will leave it up to you to read that article if you are unfamiliar with that concept
Python “if not”: Explained with Examples!
Next let us see how to use combinations of AND, OR conditions in Python.
“if” statement with combinations of AND/OR conditions
As you might have already guessed, this is pretty straight forward in python, just write down your conditions and put the operators “and” and “or” wherever you think is most appropriate!
Let us see an example!
a = 10 b = 20 c = 30 d = 40 if (a > b) or (b < c) and (c < d): print ("True") else: print ("False")
what do you think will get printed here? True or False?
Let me give you a clue from the python.org documentation
Python evaluates expressions from left to right.
This means in our example above python has evaluated the expressions in the following order
- (a > b) gets evaluated to False
- (b < c) gets evaluated to True
- (c < d) gets evaluated to True
Then line-6 becomes
if False or True and True:
Now since expressions are evaluated from left to right, the bolded part below gets executed first
False or True and True
and the if statement will become
if True and True
which then obviously evaluates to “True” and we get the output as shown below!
Best Practice #1: Use Parenthesis
Better practice to follow is to use parenthesis to indicate the order in which we want python to evaluate stuff.
So better way of writing the above code is
if ((a > b) or (b < c)) and (c < d):
This way, python or any other language for that matter, is guaranteed to evaluate ((a > b) or (b < c)) and (c < d) separately, and we don’t have to worry about nuances of the language anymore!
Best Practice #2: Use Functions to hide away complicated expressions
If your expression becomes too complicated like the example in the previous section, then I suggest using a function as shown below.
def conditionTrue(a, b, c, d): return ((a > b) or (b < c)) and (c < d) if conditionTrue(a, b, c, d): print("True")
As you can see, now the code is much more readable and will be easier to maintain!
And with that, I will end this article!
I hope you had a great time reading it as I did writing it up!
Feel free to share it with your friends and colleagues!
If your thirst for knowledge hasn’t been quenched yet, here are some more articles that might interest you!