16. Conditional Statements
By Bernd Klein. Last modified: 13 Oct 2023.
Decision Making
Do you belong to those people who find it hard to make decisions? In real life, I mean. In certain circumstances, some decisions in daily life are unavoidable, e.g. people have to go their separate ways from time to time, as our picture shows. We all have to make decisions all the time, ranging from trivial issues like choosing what to wear in the morning, what to have for breakfast, right up to life-changing decisions like taking or changing a job, deciding what to study, and many more. However, there you are, having decided to learn more about the conditional statements in Python.
Conditions - usually in the form of if statements - are one of the key features of a programming language, and Python is no exception. You will hardly find a programming language without an if statement.1 There is hardly a way to program without branches in the code flow, at least if the code needs to solve a useful problem.
A decision must be made when the script or program comes to a point where there is a selection of actions, i.e. different calculations from which to choose.
The decision, in most cases, depends on the value of variables or arithmetic expressions. These expressions are evaluated using the Boolean True or False values. The instructions for decision making are called conditional statements. In a programming language, therefore, the parts of the conditional statements are executed under the given conditions. In many cases there are two code parts: One which will be executed, if the condition is True, and another one, if it is False. In other words, a branch determines which of two (or even more) program parts (alternatives) will be executed depending on one (or more) conditions. Conditional statements and branches belong to the control structures of programming languages, because with their help a program can react to different states that result from inputs and calculations.
Live Python training
See our Python training courses
Conditional Statements in Real Life

The principle of the indentation style is also known in natural languages, as we can deduce from the following text:
If it rains tomorrow, I'll clean up the basement.
After that, I will paint the walls. If there is
any time left, I will file my tax return.
Of course, as we all know, there will be no time left to file the tax return. Jokes aside: in the previous text, as you see, we have a sequence of actions that must be performed in chronological order. If you take a closer look at the text, you will find some ambiguity in it: is 'the painting of the walls' also related to the event of the rain? Will the tax declaration be done with or without rain? What will this person do, if it does not rain? Therefore, we extend the text with additional alternatives:
If it rains tomorrow, I'll clean up the basement.
After that I will paint the walls. If there is
any time left, I will file my tax return. Otherwise,
i.e. if it will not rain, I will go swimming.
In the evening, I will go to the cinema with my wife!
It is still nor clear. Can his wife hope to be invited to the cinema? Does she have to pray or hope for rain? To make the text clear, we can phrase it to be closer to the programming code and the Python coding style, and hopefully there will be a happy ending for his wife:
If it rains tomorrow, I will do the following:
- Clean up the basement
- Paint the walls
- If there is any time left, I will make my
tax declaration
Otherwise I will do the following:
- Go swimming
Going to the movies in the evening with my wife
We can also graphically depict this. Such a workflow is often referred to in the programming environment as a so-called flowchart or program schedule (PAP):

To encode conditional statements in Python, we need to know how to combine statements into a block. So this seems to be the ideal moment to introduce the Python Block Principle in combination with the conditional statements.
Combining Statements into Blocks
In programming, blocks are used to treat sets of statements as if they were a single statement. A block consists of one or more statements. A program can be considered a block consisting of statements and other nested blocks. In programming languages, there exist various approaches to syntactically describing blocks: ALGOL 60 and Pascal, for example, use "begin" and "end", while C and similar languages use curly braces "{" and "}". Bash has another design that uses 'do ... done' and 'if ... fi' or 'case ... esac' constructs. All these languages have in common is that the indentation style is not binding. The problems that may arise from this will be shown in the next subchapter. You can safely skip this, if you are only interested in Python. For inexperienced programmers, this chapter may seem a bit difficult.
Excursion to C
For all these approaches, there is a big drawback: The code may be fine for the interpreter or compiler of the language, but it can be written in a way that is poorly structured for humans. We want to illustrate this in the following "pseudo" C-like code snippet:
if (raining_tomorrow) {
tidy_up_the_cellar();
paint_the_walls();
if (time_left)
do_taxes();
} else
enjoy_swimming();
go_cinema();
We will add a couple of spaces in front of calling 'go_cinema'. This puts this call at the same level as 'enjoy_swimming':
if (raining_tomorrow) {
tidy_up_the_cellar();
paint_the_walls();
if (time_left)
do_taxes();
} else
enjoy_swimming();
go_cinema();
The execution of the program will not change: you will go to the cinema, whether it will be raining or not!
However, the way the code is written falsely suggests that you will only go to the
cinema if it does not rain. This example shows the possible ambiguity
in the interpretation of C code by humans. In other words, you can inadvertently write the code,
which leads to a procedure that does not "behave" as intended.
In this example lurks even another danger. What if the programmer had just forgotten to put the last statement out of the curly braces?
Should the code look like this:
if (raining_tomorrow) {
tidy_up_the_cellar();
paint_the_walls();
if (time_left)
do_taxes();
} else {
enjoy_swimming();
go_cinema();
}
In the following program you will only go to the cinema, if it is not a rainy day. That only makes sense if it's an open-air cinema.
The following code is the right code to go to the movies regardless of the weather:
if (raining_tomorrow) {
tidy_up_the_cellar();
paint_the_walls();
if (time_left)
do_taxes();
} else {
enjoy_swimming();
}
go_cinema();}
The problem with C is that the way the code is indented has no meaning for the compiler, but it can lead to misunderstanding, if misinterpreted.
This is different in Python. Blocks are created with indentations, in other words, blocks are based on indentation. We can say "What you see is what you get!"
The example above might look like this in a Python program:
if raining_tomorrow:
tidy_up_the_cellar()
paint_the_walls()
if time_left:
do_taxes()
else:
enjoy_swimming()
go_cinema()
There is no ambiguity in the Python version. The cinema visit of the couple will take place in any case, regardless of the weather. Moving the go_cinema() call to the same indentation level as enjoy_swimming() immediately changes the program logic. In that case, there will be no cinema if it rains.
We have just seen that it is useful to use indentations in C or C++ programs to increase the readability of a program. For the compilation or execution of a program they are but irrelevant. The compiler relies exclusively on the structuring determined by the brackets. Code in Python, on the other hand, can only be structured with indents. That is, Python forces the programmer to use indentation that should be used anyway to write nice and readable codes. Python does not allow you to obscure the structure of a program by misleading indentations.
Each line of a code block in Python must be indented with the same number of spaces or tabs. We will continue to delve into this in the next subsection on conditional statements in Python.
Conditional statements in Python
The if statement is used to control the program flow in a Python program.
This makes it possible to decide at runtime whether certain program parts should be executed or not.
The simplest form of an if statement in a Python program looks like this:
if condition:
statement
statement
# further statements, if necessary
The indented block is only executed if the condition 'condition' is True. That is,
if it is logically true.
The following example asks users for their preferred anguage.
The indented block will only be executed if the preferred anguage is "french".
If the user enters another preferred anguage, nothing happens.
language = input("Your preferred language? ")
if language == "french":
print("Préférez-vous parler français?")
OUTPUT:
Préférez-vous parler français?
Please note that if "French" is entered in the above program, nothing will happen. The check in the condition is case-sensitive and in this case only responds when "french" is entered in lower case. We now extend the condition with an "or"
language = input("Your preferred language? ")
if language == "french" or language == "French":
print("Préférez-vous parler français?")
OUTPUT:
Préférez-vous parler français?
We still have the problem that the language will not be recognized, if somebody types in "fRench" instead of "French". This misspelling quite often occurs when somebody types very fast. An esay way to cover this problem and similar problems consists in using the "lower" method.
language = input("Your preferred language? ")
if language.lower() == "french":
print("Préférez-vous parler français?")
OUTPUT:
Préférez-vous parler français?
The Italian colleagues might now feel disadvantaged because Italian speakers were not considered. We extend the program by another if statement.
language = input("Preferred language? ")
if language.lower() == "french":
print("Préférez-vous parler français?")
if language.lower() == "italian":
print("Preferisci parlare italiano?")
OUTPUT:
Preferisci parlare italiano?
This little script has a drawback. Suppose that the user enters "french" as a preferred language. In this case, the block of the first "if" will be executed. Afterwards, the program checks if the second "if" can be executed as well. This doesn't make sense, because we know that the input "french" does not match the condition "italian" or "Italian". In other words: if the first 'if' matched, the second one can never match as well. In the end, this is an unnecessary check when entering "french" or "French".
We solve the problem with an "elif" condition. The 'elif' expression is only checked if the expression of a previous "elif" or "if" was false.
language = input("Your preferred language? ")
if language.lower() == "french":
print("Préférez-vous parler français?")
elif language.lower() == "italian":
print("Preferisci parlare italiano?")
else:
print("You are neither French nor Italian.")
print("So, let us speak English!")
OUTPUT:
Préférez-vous parler français?
As in our example, most if statements also have "elif" and "else" branches. This means, there may be more than one "elif" branches, but only one "else" branch. The "else" branch must be at the end of the if statement. Other "elif" branches can not be attached after an 'else'. 'if' statements don't need either 'else' nor 'elif' statements.
The general form of the if statement in Python looks like this:
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
...
elif another_condition:
another_statement_block
else:
else_block
If the condition "condition_1" is True, the statements of the block statement"_block_1" will be executed. If not, condition_2 will be evaluated. If "condition_2" evaluates to True, statement"_block_2" will be executed, if condition_2 is False, the other conditions of the following elif conditions will be checked, and finally if none of them has been evaluated to True, the indented block below the else keyword will be executed.
Let us add some more elif branches and languages to our previous example:
language = input("Your preferred language? ")
if language.lower() == "french":
print("Préférez-vous parler français?")
elif language.lower() == "italian":
print("Preferisci parlare italiano?")
elif language.lower() == 'spanish':
print('¿Prefiere hablar español?')
elif language.lower() == "turkish":
print("Sen Türkçe konuşmayı biliyor musun?")
elif language.lower() == "ukrainian":
print("Ви б хотіли говорити українською?")
elif language.lower() == "russian":
print("Предпочитаете ли Вы говорить по-русски?")
elif language.lower() == "greek":
print("Προτιμάτε να μιλάτε ελληνικά;")
else:
print("So, let us speak English!")
OUTPUT:
Sen Türkçe konuşmayı biliyor musun?
Live Python training
See our Python training courses
Another Example with if condition
For children and dog lovers it is an interesting and frequently asked question how old their dog would be if it was not a dog, but a human being. To calculate this task, there are various scientific and pseudo-scientific approaches. An easy approach can be:
A one-year-old dog is roughly equivalent to a 14-year-old human being
A dog that is two years old corresponds in development to a 22 year old person.
Each additional dog year is equivalent to five human years.
The following example program in Python requires the age of the dog as the input and calculates the age in human years according to the above rule. 'input' is a statement, where the program flow stops and waits for user input printing out the message in brackets:
age = int(input("Age of the dog: "))
print()
if age < 