python-course.eu

16. Conditional Statements

By Bernd Klein. Last modified: 13 Oct 2023.

Decision Making

Gender Decision

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

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Enrol here

Conditional Statements in Real Life

Mainz Psalter, example of indentation in books

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):

Flowchart Example

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.

Live Python training

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Upcoming online Courses

Enrol here

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

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Enrol here

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 < 0:
    print("This cannot be true!")
elif age == 0:
    print("This corresponds to 0 human years!")
elif age == 1:
    print("Roughly 14 years!")
elif age == 2:
    print("Approximately 22 years!")
else:
    human = 22 + (age -2) * 5
    print("Corresponds to  " + str(human) + " human years!")

OUTPUT:

Corresponds to  62 human years!

This code can be written in a better style, if we save the human age in a variable and use only one print at the end.

dog_age = int(input("Age of the dog: "))
print()
if dog_age <= 0:
    human_age = -1
elif dog_age == 1:
    human_age = 14
else:
    # this means: dog_age >= 2:
    human_age = 22 + (dog_age - 2) * 5

if human_age > 0:
    print("Corresponds to  " + str(human_age) + " human years!")
else:
    print("Negative values or zero makes no sense for a dog age!")

OUTPUT:

Corresponds to  32 human years!

We will use the previous example again in our tutorial Using if statements within programs can easily lead to complex decision trees, i.e. every if statements can be seen like the branches of a tree.

We will read in three float numbers in the following program and will print out the largest value:

x = float(input("1st Number: "))
y = float(input("2nd Number: "))
z = float(input("3rd Number: "))

if x > y and x > z:
    maximum = x
elif y > x and y > z:
    maximum = y
else:
    maximum = z

print("The maximal value is: " + str(maximum))

OUTPUT:

The maximal value is: 6.0

There are other ways to write the conditions like the following one:

x = float(input("1st Number: "))
y = float(input("2nd Number: "))
z = float(input("3rd Number: "))

if x > y:
    if x > z:
        maximum = x
    else:
        maximum = z
else: 
    if y > z:
        maximum = y
    else:
        maximum = z

print("The maximal value is: " + str(maximum))

OUTPUT:

The maximal value is: 34.0

Another way to find the maximum can be seen in the following example. We are using the built-in function max, which calculates the maximum of a list or a tuple of numerical values:

x = float(input("1st Number: "))
y = float(input("2nd Number: "))
z = float(input("3rd Number: "))

maximum = max((x,y,z))

print("The maximal value is: " + str(maximum))

OUTPUT:

The maximal value is: 16.0

Ternary if Statement

Let's look at the following English sentence, which is valid in Germany :

The maximum speed is 50 if we are within the city, otherwise it is 100.

This can be translated into ternary Python statements:

inside_city_limits = True
maximum_speed = 50 if inside_city_limits else 100
print(maximum_speed)

OUTPUT:

50

This code looks like an abbreviation for the following code:

im_ort = True
if im_ort:
    maximale_geschwindigkeit = 50  
else:
    maximale_geschwindigkeit = 100
print(maximale_geschwindigkeit)

OUTPUT:

50

But it is something fundamentally different. "50 if inside_city_limits else 100" is an expression that we can also use in function calls.

Live Python training

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Enrol here

Exercises

Exercise 1

Write a Python program that checks the temperature and provides a message based on the temperature value. If the temperature is above 27 degrees Celsius, it should print "It's a hot day." If the temperature is 27 degrees or below, it should print "It's not a hot day."

Exercise 2

Write a Python program that calculates and displays a letter grade for a given numerical score based on the following grading scale:

    A: 90-100
    B: 80-89
    C: 70-79
    D: 60-69
    F: 0-59

Exercise 3

Write a Python program that classifies a person's age into one of the following categories: "Infant," "Child," "Teenager," "Adult," or "Senior." The program should ask the user for their age and then display the corresponding classification based on the following guidelines:

    Infants: 0-2 years old
    Children: 3-12 years old
    Teenagers: 13-19 years old
    Adults: 20-64 years old
    Seniors: 65 years old and older

Exercise 4

A leap year is a calendar year containing an additional day added to keep the calendar year synchronized with the astronomical or seasonal year. In the Gregorian calendar, each leap year has 366 days instead of 365, by extending February to 29 days rather than the common 28. These extra days occur in years which are multiples of four (with the exception of centennial years not divisible by 400). Write a Python program, which asks for a year and calculates, if this year is a leap year or not.

Exercise 5

Body mass index (BMI) is a value derived from the mass (weight) and height of a person. The BMI is defined as the body mass divided by the square of the body height, and is universally expressed in units of kg/m2, resulting from mass in kilograms and height in metres. $ BMI = \frac{m}{l^{2}}$ Write a program, which asks for the length and the weight of a person and returns an evaluation string according to the following table:

BMI Evaluation

Exercise 6

Write a Python program that calculates and displays a student's final grade based on their scores for various components of a course. The program should take into account scores for homework assignments, quizzes, and a final exam. It should also consider the course grading policy:

Solutions

Solution to Exercise 1

temperature = float(input("Enter the temperature in degrees Celsius: "))

if temperature > 27:
    print("It's a hot day.")
else:
    print("It's not a hot day.")

OUTPUT:

It's a hot day.

Solution to Exercise 2

score = int(input("Enter your numerical score: "))

if score >= 90 and score <= 100:
    print("Your grade is A.")
elif score >= 80 and score < 90:
    print("Your grade is B.")
elif score >= 70 and score < 80:
    print("Your grade is C.")
elif score >= 60 and score < 70:
    print("Your grade is D.")
else:
    print("Your grade is F.")

OUTPUT:

Your grade is B.

Alternatively, you can write the program like this:

score = int(input("Enter your numerical score: "))

if 90 <= score <= 100:
    print("Your grade is A.")
elif 80 <= score < 90:
    print("Your grade is B.")
elif 70 <= score < 80:
    print("Your grade is C.")
elif 60 <= score < 70:
    print("Your grade is D.")
else:
    print("Your grade is F.")

OUTPUT:

Your grade is F.

Solution to Exercise 3

age = int(input("Enter your age: "))

if age >= 0 and age <= 2:
    print("You are an infant.")
elif age >= 3 and age <= 12:
    print("You are a child.")
elif age >= 13 and age <= 19:
    print("You are a teenager.")
elif age >= 20 and age <= 64:
    print("You are an adult.")
else:
    print("You are a senior.")

OUTPUT:

You are an adult.

Alternatively, you can write the solution like this:

age = int(input("Enter your age: "))

if 0 <= age <= 2:
    print("You are an infant.")
elif 3 <= age <= 12:
    print("You are a child.")
elif 13 <= age <= 19:
    print("You are a teenager.")
elif 20 <= age <= 64:
    print("You are an adult.")
else:
    print("You are a senior.")

OUTPUT:

You are an adult.

Solution to Exercise 4

We will use the modulo operator in the following solution. 'n % m' returns the remainder, if you divide (integer division) n by m. '5 % 3' returns 2 for example.

year = int(input("Which year? "))

if year % 4:
    # not divisible by 4
    print("no leap year")
elif year % 100 == 0 and year % 400 != 0:
    print("no leap year")
else:
    print("leap year")
    

OUTPUT:

no leap year

Another way to formulate the leap year problem:

year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(year, "is a leap year.")
else:
    print(year, "is not a leap year.")

OUTPUT:

2000 is a leap year.

Solution to Exercise 5:

height = float(input("What is your height in metres? "))
weight = float(input("What is your weight in kg? "))

bmi = weight / height ** 2
print(bmi)
if bmi < 15:
    print("Very severely underweight")
elif bmi < 16:
    print("Severely underweight")
elif bmi < 18.5:
    print("Underweight")
elif bmi < 25:
    print("Normal (healthy weight)")
elif bmi < 30:
    print("Overweight")
elif bmi < 35:
    print("Obese Class I (Moderately obese)")
elif bmi < 40:
    print("Obese Class II (Severely obese)")
else:
    print("Obese Class III (Very severely obese)")

OUTPUT:

23.301094832264035
Normal (healthy weight)

Solution to Exercise 6:

homework_score = float(input("Enter your homework score (out of 100): "))
quiz_score = float(input("Enter your quiz score (out of 100): "))
exam_score = float(input("Enter your final exam score (out of 100): "))

# Calculate the final grade based on the grading policy
homework_weight = 0.20
quiz_weight = 0.30
exam_weight = 0.50

final_grade = (homework_score * homework_weight 
               + quiz_score * quiz_weight 
               + exam_score * exam_weight)

# Determine the letter grade based on the final grade
if final_grade >= 90:
    letter_grade = "A"
elif final_grade >= 80:
    letter_grade = "B"
elif final_grade >= 70:
    letter_grade = "C"
elif final_grade >= 60:
    letter_grade = "D"
else:
    letter_grade = "F"

# Print the final grade and letter grade
print("Your final grade is:", final_grade)
print("Your letter grade is:", letter_grade)

OUTPUT:

Your final grade is: 54.0
Your letter grade is: F

Live Python training

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Enrol here

Footnotes

1 LOOP is a programming language without conditionals, but this language is purely pedagogical. It has been designed by the German computer scientist Uwe Schöning. The only operations which are supported by LOOP are assignments, additions and loopings. But LOOP is of no practical interest and besides this, it is only a proper subset of the computable functions.

Live Python training

instructor-led training course

Enjoying this page? We offer live Python training courses covering the content of this site.

See: Live Python courses overview

Upcoming online Courses

Enrol here