Conditional statements in python tutorial

In our daily lives we have decisions to make. For example, if it’s raining outside then grab an umbrella, else leave it at home. If it’s the weekend then go to the illest party in town, else go to bed early for work tomorrow. Well, humans are not the only ones that have decisions to make. Computer programs do too, and some of these decisions are quite complex. Python developers can also add decision making capabilities into their programs through conditional statements such as the if, else, and elif statements.

if statement in python

The if statement is the most basic conditional statement in python. The syntax for it is as follows:


The above statement translated into concrete python is listed below:

>>> x, y = 1, 2
>>> if x < y:
...        print('x > y equals {}'.format(x, y))
x > y equals 1

The if statement checks the boolean expression which evaluates that the combination of variables, constants, and functions reduces to True or False. This is influenced by a branch in mathematics known as boolean algebra which is named after the British mathematician George Boole.

As mentioned previously, boolean expressions evaluates to either True or False. In python and many programming languages there are builtin values for True and False; alternatively, 1 can represent True and 0 can represent False. Below is a table that shows the values you get when you combine True and False with respective operators like and, or, and xor:

x y x and y x V y x not x
0 0 0 0 0 1
1 0 0 1 1 0
0 1 0 1
1 1 1 1

Here’s a little shortcut: and (bitwise conjunction) is always false except when combining two true expressions; or (bitwise disjunction) is always true except when combining two false expressions, and xor (exclusive or) is false when both expressions are true/false. If you know how to interpret the truth table, and have an understanding of python syntax, then you have the knowledge needed to write conditional statements. Let’s get some practice evaluating the truthfulness of expressions in python:

>>> True and False
>>> True and True
>>> True and True
>>> False and False
>>> True & False
>>> True or False
>>> True or True
>>> False or False
>>> not False
>>> not True
>>> False ^ True
>>> False ^ False
>>> True ^ True

Let’s combine python syntax with boolean algebra:

>>> if True and True:
...         print('True')

The expression evaluates to true because according to the truth table two true expressions ANDed together are True.

>>> if False or True:
...        print('True')

As again, if you refer to the truth table you can see that a False expression OR’ed with a True one evaluates to True. Let’s look at the following example:

>>> if (True and False) == (False and False):
...         print("They're equal")

They're equal

You can include more than one expression in a conditional statement. Since True and False evaluates to False, and False and False is also equal to False, the two expressions are thus equal.

else keyword

An else statement is one that can be combined with an if statement. The else statement is only executed if the conditional expression in the if statement resolves to false or 0. The else statement is optional, and follows an if statement. Below is an example of an if/else statement in action:

>>> x, y = 5, 2
>>> if x > y:
...        print('{} > {} = {}'.format(x, y, x > y))
... else:
...     print('{} < {} = {}'.format(x, y, x < y))

5 > 2 = True

The elif statement in python

The elif statement allows programmers to verify multiple expressions for truthfulness, and execute a block of code as soon as one of the conditions evaluates to True. The elif statement is similar to the else statement in that it too immediately follows the if statement, but it’s different in that multiple elif statements are allowed or can be chained together. The below code snippet shows how to use elif statements to verify a corresponding letter grade for a number.

>>> grade = 80
>>> if grade >= 90:
...     print('A')
... elif grade >= 80 and grade < 90:
...     print('B')
... elif grade >= 70 and grade < 80:
...     print('C')
... elif grade >= 60 and grade < 69:
...     print('D')
... else:
...     print('F')

Nested conditional statements

Python permits nested conditional statements or a conditional within a conditional. Below is an example of a nested if statement in python:

>>> x, y, z = 1, 2, 3
>>> if x < y:
...         if y < z:
...             if x + y == z:
...                 print('{} + {} = {}'.format(x, y, z))
...             else:
...                 print('{} + {} is not equal to {}'.format(x, y, z))
...         else:
...             print('{} is not less than {}'.format(x, y))
... else:
...     print('{} is not less than {}'.format(x, y))
1 + 2 = 3

In the above example since the first two if expressions are true, the third expression is evaluated. You can modify the variables to see how it will affect the result.

Conditional expressions

Python enables conditional expressions which are similar to ternary expressions found in other languages. Conditional expressions were added in python 2.5. It’s important to note that conditions are expressions therefore you can't use statements like for or pass. If a statement is needed then you should default to using the normal if statement. Below is an example of a conditional expression in python:

>>> x, y, z = 1, 3, 2
>>> express_1 = x if y - z == 1 else 2
>>> express_1
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.