Python simple decision making

Jeremiah Taguta (BSc in Computer Science, Masters in Information Systems)
Published on 11-09-2023
Mastering Conditional Logic: A Beginner's Guide to If, Elif, and Else Statements in Python

Many times, any rational being has to make decisions which are based on existing conditions. For instance, if you want to take a walk when it is raining but you don't want to get wet, you take an umbrella. The decision is "take an umbrella" and the conditions are "it's raining and you don't want to get wet". This intelligence or decision-making process can be engrafted even in the programs we write in Python.

Having covered relational and logical operators before, this piece shall dwell on if, if else and if elif else structure in Python.

a. If statement

This follows the following structure:

if condition: 

The syntax is that the if statement has to end with a full colon and its body should be indented to the right. Anything not indented is not the body of the statement.

The if statement is used to test a condition. A condition is a logic proposition, that is, a statement that can be True or False. The condition can be a simple relational operator. If the condition evaluates to True or is True, the body of the if statement is executed. If the condition is False, the body of the if statement is not executed.

We are going to use the following variables for some of our example programs

1 num1 = 5
2 num2 = 10
3 num3 = 15
To demonstrate an if statement, we are going to write a program which tells us if num1 is less than num2 as shown below.
1 if num1 < num2:
2     print(num1, "is less")
3 print("I'm outside if")

In the above example, the condition in line 1, num1 < num2, is correct as 5 is less than 10 hence the body of the if statement is executed showing us the print output, "5 is less". In line 3, the print function is implemented after the body of the if statement is executed. This shows that an if statement can be surrounded by any other code.

What will happen if we change the condition to test if num1 > num2 while maintaining the body of the if statement? See below example,

1 if num1 > num2:
2     print(num1, "is greater")
In line 1 above, the condition is evaluated as False as num1, a 5, is not greater than num2, a 10. As such, the body of the if statement is not executed and nothing is seen as a result of the processing.

The issue then becomes, since the body of the if statement is not executed because the if condition is False, can't we still display that the opposite is happening? For instance, if num1 > num2 is False and the body of the if is not run, can't we display the reverse Otherwise the absence of display may be misconstrued for an error?

The solution to that exists, it is the "if else statement"

b. If else statement

The structure is as follows:

if condition: 

If the if condition is True, the if body is executed otherwise the body of the else statement is executed. An if-else structure thus works if there are 2 possible paths or decisions to be made. See the below example to show the greater of 2 numbers.

1 if num1 > num2:
2     print(num1, "is greater")
3 else:
4     print(num2, "is greater")

In line 1, the if condition is False as num1, a 5, is not greater than num2, a 10, so the body of the if is not executed. Because the if condition is False, the Else body is executed thus displaying "10 is greater"

i. A program to tell if the user number is even

We need to fetch the user number as in line 1 below and test if the remainder is a 0 when a user number is divided by 2 as in line as an even number should be divisible by 2 without leaving a remainder.

1 user_num = int(input("Enter a number : "))
2 if user_num % 2 == 0:
3     print(user_num, "is even")
4 else:
5     print(user_num, "is odd")
In the above example, line 1, if a user puts a 5, 5 divided by 2 leaves a remainder 1, which is not equal to 0 hence the else body will be executed. The reverse is true if an even number, 20, is entered. Take note that in the above example, we used a relational equality operator thus one can use the best operator for the task at hand.
ii. The greatest of 3 numbers program using if else statements
We want to write a program to find the greatest of three numbers. For this to be possible, we need to use if else statements inside if and else statements thus if else statement nesting.
Thinking ... for the first number to be greatest, it has to be bigger than the second and third numbers. For the second number to be greatest, it has to be bigger than both the first and third numbers. Finally, for the third number to be greatest, it has to be bigger than both the first and second numbers. Having explained the logic, the following is the code for the program, using our already declared num1 as 5, num2 as 10 and num3 as 15. You may fetch values of your choice as explained in another previous article.

NB: Take note of the code comments for explanations

1  # Compare the numbers to find the greatest
2  if num1 >= num2:
3     # executed when num1 is greater than num2
4      if num1 >= num3:
5          # executed when num1 is greater than num3 when num1 is greater than num3
6          greatest = num1
7      else:
8          # executed when num3 is greater than num2 when num1 is greater than num3
9          greatest = num3
10 else:
11     # executed when num1 is not greater than num2, i.e num1 less than num3
12    if num2 >= num3:
13         # executed when num2 is greater than num3 when num1 is less than num2
14         greatest = num2
15    else:
16         # executed when num3 is greater than num2 when num1 is less than num2
17         greatest = num3

18 # Print the result
19 print("The greatest of ", num1,",", num2, "and", num3, "is", greatest)
Looking at the above example, the output is"The greatest of 5, 10 and 15 is 15" as explained in the code comment on the circumstances under which different parts of the code can be executed.
c. If elif else
We said an if statement works for only one path or decision, if else statement works for 2 possible paths or decisions, what about if we have more than 2 paths or decisions to be made?
That is where we can use the if elif else statement for every possible decision for every possible condition. The elif means else if.
The structure of the if elif else structure is as follows:
if condition 1:
   body 1
elif condition 2:
   body 2
elif condition 3:
   body 3
   body n
If condition 1 is True, body  1 is executed, if condition 2 is True, body 2 is executed, if condition 3 is True, body 3 is executed and this goes on and on for every body whose if condition is True. If all the if and elif statement conditions are False, the else body is executed.
i. Grading program
A grading program where marks 80 - 100 is an A, 70 - 79.9... is a B, 60 - 69.9... is a C, 50 - 59.9... is a D, 40 - 49.9... is an E and 0 - 39.9... is a F.
One can be like Can't we write this program with only if statements? Let's see what happens with the below example. We assume no user will enter a mark above 100 and below 0 otherwise it will be invalid based on lines 2 and 16.
mark = 75 # float(input("Enter a mark for grading :"))
1  if mark > 100:
2      print("Invalid mark")
3  if mark >= 80:
4      print("A")
5  if mark >= 70:
6      print("B")
7  if mark >= 60:
8      print("C")
9  if mark >= 50:
10     print("D")
11 if mark >= 40:
12     print("E")
13 if mark > 0:
14     print("F")
15 else:
16     print("Invalid mark")
As you can see in the above example, lines 6, 8, 10, 12 and 14 conditions are all True hence the outputs are "B C D E F" which is not what we expect. A series of if statements will have their bodies executed as long as their conditions are True. We expected a B since a mark of 75 is a "B" but after printing a "B", the program continues to run all if statements comparing their conditions. If the conditions are not True, for instance, in line 4, our mark is not greater than 80 so the if statement body is not executed.

The question is, "How can we stop further comparison after one if statement condition becomes True?". To achieve this, we use the elif statement. It stops further comparisons after one of the if /elif conditions becomes True. The else is run if all if and elif conditions are False. See the below example depicting that.

1  mark = 75 # float(input("Enter a mark for grading :"))
2  if mark > 100:
3      print("Invalid mark")
4  elif mark >= 80:
5     print("A")
6  elif mark >= 70:
7      print("B")
8  elif mark >= 60:
9      print("C")
10 elif mark >= 50:
11     print("D")
12 elif mark >= 40:
13    print("E")
14 elif mark >= 0:
15    print("F")
16 else:
17    print("Invalid mark")
Now, after lines 2, and 4 conditions are evaluated as False, the line 6 condition is evaluated as True thus its body is executed, displaying a "B". Because we are using the if elif statements, no further comparisons are done for elif statements after line 6. The else body is not executed as well because one of the previous elif conditions, that is, line 6, evaluated True. As discussed before, the else body is run if none of the top conditions of if and elif statements are True.
As I conclude this piece, all the conditions of the if and elif statements were simple comparisons but the condition can be complex thus 2 or more relational operators joined by logic operators. This we shall cover in the next article.
Thanks for reading. If you have any questions, feel free to ask in the comments section, I'll gladly help. Check out my programming tutorials on YouTube and don't forget to subscribe, comment, like, and share on both YouTube and on this Blog. Lets code together!!!

163 Like

Drop your comment

© Copyright 2023 Jeremiah Taguta. All Rights Reserved.

Product of ‌

Jeremiah Taguta T/A Charis Technologies