Home Python Course #7: Conditional Statments if, else and elif
Post
Cancel

Python Course #7: Conditional Statments if, else and elif

After learning a lot about Boolean algebra, binary numbers and how to add, subtract, multiply and divide them let’s get back to programming Python. The first couple of programs you have written so far are static and don’t have any dynamic behavoir. That means the program data stored in variables does not have an effect on the programs output. But this changes now with the introduction of conditional statments.

Static vs. Dynamic Program Flow

In a static program all statements are executed exactly one time one after another. When introducing conditional statements some parts of a program aren’t executed while others are. To show the difference between a static and dynamic have a look at this flow chart:

Static vs. Dynamic Flow Chart

A flow chart usually goes from top to bottom while the filled circle is the program start and the circle with a ring inside is an end of the program (a program can have several ends but only one start) the direction of the program flow is indicated by the arrows going to different diagram elements. On the left-hand side you can see a static program first 42 is assigned to x, then 23 is assigned to y, afterwards x*y is stored in z, and finally z is printed. The flow chart on the right-hand side start with the same x = 42 statement but then follows a diamond-shaped element. In this diamond-shape the condition x > 10 is stated. If x is greater than 10 the statement evaluates to True if x is equal or less than 10 the condition is evaluated to False. And according to the evaluation result the program flow follows the arrow marked with the evaluation result. So in this particular example the program will follow the arrow marked with True and execute the statement y = 23. The statement y = -12 is not going to be executed. Afterwards the two branches coming from a conditional can be merged in a subsequent statement which is print(z) in this flow chart.

Comparision Operators

Now lets write the flow chart on the right-hand side in Python code:

1
2
3
4
5
6
7
8
9
10
if __name__ == "__main__":
    x = 42

    if x > 10:
        y = 23
    else:
        y = -12

    z = x*y
    print(z)

In line 4 you can find an if ... : statement and everything that is indented under the if statement will be executed when the condition x > 10 evaluates to True which is the case for the current assignment of x = 42. When you change x to a value equal or less than 9 the condition x > 10 evaluates to False and non of the statements indented und the if ... : statement will be executated. But immediately after the last statement indented after the if ... : statement comes and else: statement. The code indented under the else: statement is only executed when the condition x > 10 evaluates to False. The if and the else represent the mutually exclusive paths in the right-hand flow chart above.

The condition of an if ... : statement can be arbitrary complex but has to evaluate to a bool True or False. The condition can include the following comparisions for numerical data (int and float) and for str lengths, except for == which compares the string content:

OperatorDescriptionExample
<less thanx < 9 is True if x is less than 9
>greater thanx > y is True if x is greater than y
==equalx == 13 is True if and only if x is 13
!=not equalx != y is True if and only if x is not y
<=less than or equalx <= 23 is True if x is 23 or less
>=less than or equalx >= y is True if x is y or greater

Combining Comparisions with Boolean Algebra

When you want to couple multiple comparisions such as:

\[10 \leq x < 20\quad y < 10 \hspace{0.5em}\text{or}\hspace{0.5em} y > 20\]

You have to use Boolean algebra operators as you have seen them in Python Course #3: Introduction to Boolean Algebra.

for example if you want the express that x has to be greater or equal than 10 and x has to be less than 20 you can write the following:

1
x >= 10 and x < 20

Taking the example from above involving y you can write:

1
y < 10 or y > 20

When combining Boolean operators with comparision operators you have to remember the Python Operator Precedence whereas comparision operators are evaluated before Boolean operators.

else-if: elif

An if does not have to be followed by an else. Which would be represented in a flow chart like this:

No Else

And the Python code for this flow chart is:

1
2
3
4
5
6
7
8
9
if __name__ == "__main__":
    x = 42
    y = 0

    if x > 10:
        y = 23

    z = x*y
    print(z)

When x is less than or equals 10 the statement y = 23 is just skipped. You probably wonder why y = 0 was added above the if statement while it wasn’t in code example including the else. When a variable is defined inside an if ... : statement it also has to be defined in all alternative paths when it should be used after the if. However, in the example there is no alternative path with x > 10 evaluates to False and therefore y = 0 is introduced because otherwise a NameError will be raised when executing z = x*y because y was never defined.

You can also add an if a so called elif statement under an if statement that is only evaluated when the if statement above evaluated to False:

Elif

Which looks like this in Python code:

1
2
3
4
5
6
7
8
9
10
11
if __name__ == "__main__":
    x = 42
    y = 0

    if x > 10:
        y = 23
    elif x > 5:
        y = -12

    z = x*y
    print(z)

You can actually add a whole chain of elif under each other while each one of them is only evaluated when the above one evaluates to False. If any elif statement is True all following statements are disregarded. After any elif you can add a else which will be executed when all of the statements above it are False.

Such a chain of if, elif and else is useful when a condition is categorical, meaning it can only be one thing and not several:

1
2
3
4
5
6
7
8
9
10
11
12
13
if __name__ == "__main__":
    name = "Mr. Fluffers"
    species = "cat"

    if species == "dog":
        print(name, "barks")
    elif species == "duck":
        print(name, "quacks")
    elif species == "cat":
        print(name, "meows")
    elif species == "cow":
        print(name, "moos")
    else:

Short-circuit Evaluation

When you got a condition composed out of several statements added together by with and and or the Python interpreter will evaluate the statements one after another from left to right. Take for example the following if statement

1
if a > 10 and b < 2

Python first checks if the comparision a > 10 evaluates to True and will then check b < 2, however, if a > 10 evaluates to False then b < 2 wont be checked due to the annulment law of the Boolean Algebra that states:

\[x \wedge 0 = 0\]

This is called short-circuit evaluation and can save time when evaluating complex conditions. But you can also use to your advantage. Have a look at the following code:

1
2
3
4
5
6
7
8
9
if __name__ == "__main__":
    x = 2

    if x == 1:
        y = 3

    if y > 4 and x == 1:
        print("success")

The first if statement will evaluate to False which means that y = 3 is not executed and because of that y is not defined an can not be used in the subsequent code. When you try to run this code it will raise a NameError that y is not defined. However, when you switch the order of the second if statement to:

1
    if x == 1 and y > 4:

The code will run without any issues. Because x == 1 evaluates to False and therefore the whole if statement evaluates to False. But I would strongly advice agains a code like this as it can get confusing very quickly. Later in this course you will make use of short-circuit evaluation in a more reasonable manner.

Ternary Operator

To assign a value to a variable based on the value of another variable is pretty common:

1
2
3
4
5
6
7
8
9
10
if __name__ == "__main__":
    name = "Sandra"
    age_years = 23

    if age_years >= 18:
        legal_status = "adult"
    else:
        legal_status = "minor"

    print(name, "is a", legal_status)

Assigning a value to legal_status requires four lines of code. But you can also write it in one line with a ternary operator. The name is derived from the fact that this operator takes 3 input values instead of 1 or 2:

1
2
3
4
5
6
7
if __name__ == "__main__":
    name = "Sandra"
    age_years = 13

    legal_status = "adult" if age_years > 18 else "minor"

    print(name, "is a", legal_status)

The ternary operator combines and if else clause into a single statement. The first input is the output if the condition evaluates to True. The second input is the condition itself and the last input is the output if the condition evaluates to False. You can go even further and remove the variable legal_status by moving the ternary operator into the print(...) statment:

1
2
3
4
5
if __name__ == "__main__":
    name = "Sandra"
    age_years = 13

    print(name, "is a", "adult" if age_years > 18 else "minor")

I would suggest to use this operation with caution as the code readability can suffer pretty quickly especially when you nest several ternary operators.

The ternary operator concludes this article. You have learned about comparision operators and how to combined them with Boolean algebra to from complex conditions for if statements, how to use if, else, and elif, what short-circuit evaluation is, and how to shortend a conditional variable assignment with a ternary operator. As always I encourage you to play around with if, else, elif and the ternary operator. If you have any questions about this article, feel free to join our Discord community to ask them over there.

This post is licensed under CC BY 4.0 by the author.