DEV Community

Cover image for Teaching Python to Make Decisions
Sharon-nyabuto
Sharon-nyabuto

Posted on

Teaching Python to Make Decisions

Understanding if, elif, and else

In the previous article, we explored what Python is and why it's such a valuable tool for data analysts. We also wrote a few simple programs that followed instructions exactly as we wrote them.

In this article, we will explore how to teach Python to make decisions using conditional statements. By the end, you'll understand how to use if, elif, and else to control the flow of your programs and hopefully solve simple real-world problems.


So what is a conditional statement?

We make decisions all the time in our lives. If it rains, we carry an umbrella. If we're hungry, we eat. If an assignment is due tomorrow, we probably shouldn't leave it until midnight. Programs need to make decisions too, that is what conditional statements are for.

Conditional Statements allow a program to evaluate conditions and choose what to do based on whether those conditions are True or False.
The three keywords you'll most commonly use when writing conditional statements are if, elif, and else.

Comparison Operators

Before we can make decisions in Python, we need a way to compare values.
Comparison operators evaluate two values and return either True or False, which are the outcomes that drive if, elif, and else statements. Common comparison operators are:

Operator Meaning
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Example:


age = 25

print(age == 25)   # equal to        -> True
print(age != 18)   # not equal to    -> True
print(age > 18)    # greater than    -> True
print(age < 18)    # less than       -> False
print(age >= 25)   # greater or equal -> True
print(age <= 20)   # less or equal    -> False

Enter fullscreen mode Exit fullscreen mode

Note: The = operator assigns a value to a variable, (like age = 25), while == checks whether two values are equal. This is one of the most common mix-ups I had when I started out.


The IF statement

The if statement is what lets your code actually make a decision : It runs a block of code only if a condition is True.

Example:

age = 25
if age >= 18:
    print("You're an adult.")
Enter fullscreen mode Exit fullscreen mode

Here's what happens step by step:

  1. age = 25 - Python stores the value 25 in the variable age.
  2. age >= 18 - It evaluates the condition.
  3. Since 25 is greater than 18 the condition is True
  4. The indented line is executed, and the output prints:
You're an adult.
Enter fullscreen mode Exit fullscreen mode

The colon : shows the end of the condition, and indicates everything after is what needs to be done if the condition is met.

The indentation (usually 4 spaces) is how Python knows which lines of code belong inside the if statement.

The ELSE statement

In an if statement, you specify what needs to be done if the condition is True.
You can also tell Python what to do if the condition is not met, using else. The statement then becomes;

Example:

score = 68
if score >= 70:
    print("You have passed")
else:  
    print("Please retake the test")
Enter fullscreen mode Exit fullscreen mode

Here's what happens step by step:

  1. Python stores the value 68 in the variable score.
  2. It evaluates the condition score >= 70.
  3. Since 68 is less than 70, the condition evaluates to False.
  4. Because the if condition is False, Python skips the if block.
  5. Python then executes the else block and prints:
Please retake the test
Enter fullscreen mode Exit fullscreen mode

The else block acts as a fallback, and is only executed when the condition in the if statement evaluates to False.

The if-else statement is always used when you have two possible outcomes.

The ELIF statement

Suppose there are more than two possible outcomes?
The if-else statements will not sufficiently represent all of them. This is where the elif statement becomes useful

elif ("else if") lets you check additional conditions in order.

Example:

age = 34

if age >= 40:
    print("Older Adults")
elif age >= 20:
    print("Youth")
else:
    print("Teens")

Enter fullscreen mode Exit fullscreen mode

Here's what happens step by step:

  1. Python stores the value 34 in the variable age.
  2. It evaluates the first condition: age >= 40.
  3. Since 34 is less than 40, the first condition evaluates to False, so Python moves to the next condition.
  4. Python evaluates the elif condition: age >= 20.
  5. Since 34 is greater than 20, the elif condition evaluates to True.
  6. Python executes the elif block and prints:
Youth
Enter fullscreen mode Exit fullscreen mode
  1. Python then skips the else block and the conditional statement ends.

Think of elif as Python saying, "If the first condition wasn't true, check this one instead."
The conditions are evaluated from top to bottom and only the first condition that evaluates to True is executed.


Putting Conditionals into Practice

Now that we've covered the basics of if, elif, and else, it's time to see how they work together.
The following examples are a little more practical, and demonstrate how Python can make decisions based on multiple conditions.

Examples

# Q1. A cinema allows entry if: age >= 18 AND has_ticket == True. Write the condition and test it with different values.

age = int(input("How old are you?")) # Ask for age
has_ticket = True

if age >= 18 and has_ticket == True:
    print("Welcome to the Movies!")
else: 
    print("Restricted")
Enter fullscreen mode Exit fullscreen mode
# Q2. Build an electricity bill calculator. Units used: 0–50 → Ksh 12/unit, 51–200 → Ksh 15/unit, 201+ → Ksh 18/unit. Ask for units used and print the total bill.

electricity_units = int(input("How many units have you used?"))
print(electricity_units)
if electricity_units <= 50:
    print("Your bill is ",electricity_units * 12)
elif electricity_units <= 200:
      print("Your bill is ",electricity_units * 15)
else:
     print("Your bill is ",electricity_units * 18)
Enter fullscreen mode Exit fullscreen mode
# Q3. Ask for a student's marks (0–100). Print their KCSE grade: A (75+), B (60–74), C (50–59), D (40–49), E (below 40).
student_marks = int(input("What were your marks?"))
if student_marks >= 75:
    print("A")
elif student_marks >= 60:
    print("B")
elif student_marks >= 50:
    print("C")
elif student_marks >= 40:
    print("D")
else:
    print("E")
Enter fullscreen mode Exit fullscreen mode

Don't worry about counting your elif statements! You can have as many as your program needs, as you can see in the last example. Python simply checks each condition in order and stops as soon as it finds one that's True.


Your turn, try it yourself!

The examples in this article are just a starting point. Experiment with different values, create your own conditions, and see how changing the logic affects the output. Programming is one of those skills that's learned best by doing.

What's Next?

We've now learned how to make Python choose between different paths. Next, we'll build on that foundation with nested if statements, where one condition is evaluated inside another. It's a small step in syntax, but a big step towards writing more realistic programs.

Thanks for reading, and I hope you'll join me for the next part of the series. Until then, happy coding!

Top comments (0)