DEV Community

Navas Herbert
Navas Herbert

Posted on

Python Week 2: We Taught Python to Make Decisions

Last week, our programs were polite but passive. They'd take your name, store your age, print a receipt - but they couldn't respond to what you gave them. Every program ended the same way no matter what you typed.

This week, that changed.

Week 2 was about teaching Python to think. Or at least, to choose. We covered operators and conditionals - the building blocks that let a program look at a value and say: "based on this, I'll do one thing and not another."

It sounds small. It's not.


First: Operators - Asking Python Yes/No Questions

Before any if statement, students needed to understand comparison operators - the tools Python uses to evaluate whether something is true or false.

I framed it simply: an operator is just a question you ask Python. It always answers yes or no.

age = 20

print(age > 18)     # Is age greater than 18?
print(age == 20)    # Is age exactly 20?
print(age != 25)    # Is age NOT 25?
print(age >= 18)    # Is age 18 or older?
print(age <= 15)    # Is age 15 or younger?
Enter fullscreen mode Exit fullscreen mode
True
True
True
True
False
Enter fullscreen mode Exit fullscreen mode

Clean. Simple. Everyone got it immediately.

Then came the mistake I wait for every single cohort.


The Mistake Everyone Makes Exactly Once

age = 20

if age = 18:
    print("You are exactly 18")
Enter fullscreen mode Exit fullscreen mode
SyntaxError: invalid syntax
Enter fullscreen mode Exit fullscreen mode

"But I used equals?"

Right. And that's the problem. In Python, = means "store this value". == means "are these the same?" They look almost identical. They do completely different things.

age = 20          # ASSIGNMENT — put 20 in the box called age
age == 20         # COMPARISON — is age the same as 20? (True/False)
Enter fullscreen mode Exit fullscreen mode

I told them: you will make this mistake. It will confuse you. You will stare at it for two minutes. Then you'll see the missing = and feel silly. That's normal. It happens to everyone, including people who've been coding for ten years.

After that, they started double-checking their equals signs. Good habit, hard-earned.


Logical Operators: Combining Questions

Sometimes one question isn't enough. We covered and, or, and not:

age = 22
has_id = True

# AND — both conditions must be True
if age >= 18 and has_id:
    print("Welcome in.")
else:
    print("Sorry, not tonight.")
Enter fullscreen mode Exit fullscreen mode
Welcome in.
Enter fullscreen mode Exit fullscreen mode

The analogy I used: a bouncer at a club in Westlands. They check your age and your ID. One isn't enough - both conditions have to pass or you're not getting in. and is the strict bouncer.

or is more relaxed:

is_student = False
has_discount_card = True

if is_student or has_discount_card:
    print("Discounted fare: KES 30")
else:
    print("Full fare: KES 50")
Enter fullscreen mode Exit fullscreen mode
Discounted fare: KES 30
Enter fullscreen mode Exit fullscreen mode

And not simply flips the answer:

is_raining = False

if not is_raining:
    print("No umbrella needed today.")
Enter fullscreen mode Exit fullscreen mode
No umbrella needed today.
Enter fullscreen mode Exit fullscreen mode

if / elif / else: The Decision Tree

Now the main event.

The structure is straightforward once you see it as a sequence of questions Python asks in order - stopping as soon as one is true:

score = 74

if score >= 80:
    print("Grade: A")
elif score >= 70:
    print("Grade: B")
elif score >= 60:
    print("Grade: C")
elif score >= 50:
    print("Grade: D")
else:
    print("Grade: F - please see your teacher")
Enter fullscreen mode Exit fullscreen mode
Grade: B
Enter fullscreen mode Exit fullscreen mode

Key rule I drilled in: Python checks from top to bottom and stops at the first True condition. It doesn't check the rest. This matters when conditions overlap:

score = 85

# WRONG — overlapping conditions, wrong order
if score >= 50:
    print("Grade: D")   # This fires for 85! Python stops here.
elif score >= 80:
    print("Grade: A")   # Never reached
Enter fullscreen mode Exit fullscreen mode
Grade: D
Enter fullscreen mode Exit fullscreen mode

Someone in the room got this wrong on their first attempt - which was exactly what I needed. We looked at the output together, traced through the logic, and found the bug. That exercise is worth more than five explanations.


The Moment That Got Everyone: The M-Pesa Checker

At the end of Week 1, I teased this program. This week we actually built it.

balance = float(input("Enter your M-Pesa balance (KES): "))

if balance >= 1000:
    print("✅ You're good. Send that money.")
elif balance >= 100:
    print("⚠️  Low balance — top up soon.")
elif balance > 0:
    print("❌ Very low. You can barely send a text.")
else:
    print("💀 Broke. Completely broke.")
Enter fullscreen mode Exit fullscreen mode

One student - Otieno - typed 0 and got the last message. He laughed so hard the whole room started laughing. Then someone else typed their actual balance just to see what Python would tell them.

That's the moment. When the program stops being an exercise and becomes something they interact with. When they're not running code — they're using software.

After that, everyone wanted to build their own version.


Nested Conditions: An If Inside an If

Once students were comfortable with basic if/elif/else, we pushed further — what if the decision has layers?

age = int(input("Enter your age: "))
has_ticket = input("Do you have a ticket? (yes/no): ")

if age >= 18:
    if has_ticket == "yes":
        print("Enjoy the show! 🎬")
    else:
        print("You're old enough, but you need a ticket first.")
else:
    print("Sorry - this show is 18+.")
Enter fullscreen mode Exit fullscreen mode
Enter your age: 22
Do you have a ticket? (yes/no): yes
Enjoy the show! 🎬
Enter fullscreen mode Exit fullscreen mode

"You can put an if inside an if?"

Yes. And you can put one inside that one too - though I warned them: deeply nested conditions are a code smell. If you're four levels deep, step back and rethink. For now, two levels is fine.


We Built This Together: Matatu Fare Calculator

The session project. Students built this step by step, from scratch:

print("=== Nairobi Matatu Fare Calculator ===")

distance = float(input("Distance in km: "))
is_peak_hour = input("Is it peak hour? (yes/no): ")

# Base fare calculation
if distance <= 5:
    fare = 50
elif distance <= 15:
    fare = 100
elif distance <= 30:
    fare = 150
else:
    fare = 200

# Peak hour surcharge
if is_peak_hour == "yes":
    fare = fare * 1.5
    print(f"Peak hour surcharge applied.")

print(f"\nDistance: {distance} km")
print(f"Total fare: KES {fare:.0f}")
Enter fullscreen mode Exit fullscreen mode
=== Nairobi Matatu Fare Calculator ===
Distance in km: 12
Is it peak hour? (yes/no): yes
Peak hour surcharge applied.

Distance: 12.0 km
Total fare: KES 150
Enter fullscreen mode Exit fullscreen mode

What I loved about this exercise: students had to think about the real world to write correct code. What counts as peak hour? What if someone enters a negative distance? What if they type "YES" instead of "yes"? Those questions came up naturally - and they're exactly the kind of edge-case thinking that makes a good programmer.


Practice Problems

Try these yourself:

Easy:

# 1. Ask the user for a number. Print whether it's positive, negative, or zero.
# 2. Ask for two numbers. Print which one is larger (or "they're equal").
# 3. Ask for a temperature in Celsius. Print "Hot" if above 30, "Cold" if below 15, "Comfortable" otherwise.
Enter fullscreen mode Exit fullscreen mode

Medium:

# A simple login checker
username = input("Enter username: ")
password = input("Enter password: ")

# Expected: username = "admin", password = "1234"
if username == "admin" and password == "1234":
    print("✅ Access granted. Welcome.")
elif username == "admin":
    print("❌ Wrong password.")
else:
    print("❌ Username not found.")
Enter fullscreen mode Exit fullscreen mode

Challenge:

# Build a simple NHIF contribution calculator
# Rules (simplified):
# Gross salary < 5,999 → KES 150
# 6,000 – 7,999 → KES 300  
# 8,000 – 11,999 → KES 400
# 12,000 – 14,999 → KES 500
# 15,000 and above → KES 600

salary = float(input("Enter gross monthly salary (KES): "))
# Your if/elif/else here...
Enter fullscreen mode Exit fullscreen mode

What I Noticed Teaching This Session

1. The = vs == error is a rite of passage - let it happen. Don't pre-warn students so much that they never make the mistake. Making it, reading the error, and fixing it themselves is how it sticks.

2. Real-world stakes make conditions more fun. The M-Pesa checker worked because students had an emotional relationship with their balance. Abstract exercises like if x > 5 don't carry that. Always anchor the condition in something that matters to them.

3. Students naturally found edge cases. Once they built the matatu calculator, they immediately started trying to break it — negative distances, letters instead of numbers. That curiosity is the beginning of a testing mindset. Don't discourage it.

4. elif takes a minute to click. A few students kept writing separate if statements instead of elif. I had to show them what goes wrong - multiple conditions firing for the same input - before they understood why elif exists.


I'm a data trainer in Nairobi running a full data programme —
Python foundations → Data Science or Data Engineering specialisations.
I write weekly about what we covered, what worked, and what surprised me.
Follow along or drop your questions in the comments.

Top comments (0)