Same deal as last time: open session2.py, keep it next to this article, type everything yourself.
Comparison Operators - Asking Yes or No Questions
Every decision starts with a question that has exactly two possible answers: True or False. That's what comparison operators give you.
age = 20
score = 75
print(age == 20) # True - age IS 20
print(age == 25) # False - age is NOT 25
print(score > 70) # True
print(score <= 74) # False - 75 is not <= 74
True
False
True
False
I flag one thing before anyone even runs this: == asks a question, = stores a value. Mixing them up is the single most common typo in this entire course - everyone does it at least once, usually while I'm mid-sentence explaining something else.
String comparisons work the same way, but with a twist:
track = "Data Science"
print(track == "Data Science") # True
print(track == "data science") # False - case sensitive!
print("Amina" < "Brian") # True - alphabetical order
True
False
True
'Data Science' and 'data science' are completely different strings to Python. If you want to compare without caring about case, lowercase both sides first: track.lower() == "data science".
if - Making a Decision
An if statement checks a condition. If it's True, the indented block runs. If it's False, Python skips it - nothing happens, no error, it just moves on. Think of it like a gate: no ID, no drama, you just don't get let in.
score = int(input("Enter your score: "))
if score >= 50:
print("You passed!")
print("Thank you for taking the test.")
Enter your score: 75
You passed!
Thank you for taking the test.
The line "Thank you for taking the test." isn't indented, so it always runs - pass or fail. Only the indented line is conditional. Run it again with a score of 30 and watch "You passed!" disappear while the thank-you stays.
else and elif - More Than One Path
else gives you the opposite path - exactly one of the two blocks runs, never both, never neither:
score = int(input("Enter your score: "))
if score >= 50:
print("PASS - Well done!")
else:
print("FAIL - Please try again.")
print(f"Your score was: {score}")
Enter your score: 45
FAIL - Please try again.
Your score was: 45
elif - short for "else if" - lets you chain more than two paths:
score = int(input("Enter score: "))
if score >= 80:
print("Grade A - Excellent!")
elif score >= 70:
print("Grade B - Good")
elif score >= 60:
print("Grade C - Average")
elif score >= 50:
print("Grade D - Below Average")
else:
print("Grade F - Failed")
Enter score: 73
Grade B - Good
Here's the part that trips people up every single cohort: Python checks top to bottom and stops at the first True condition. Order the boundaries wrong - say, checking score >= 50 before score >= 80 - and every passing score gets swallowed by the first, loosest condition before Python ever reaches the accurate one. Always put the most specific condition first.
Logical Operators - Checking More Than One Thing
Sometimes one question isn't enough. and needs both conditions True. or needs at least one. not flips True to False and back.
age = int(input("Age: "))
has_id = input("Do you have an ID? (yes/no): ")
if age >= 18 and has_id == "yes":
print("Access granted - welcome!")
else:
print("Access denied.")
Age: 20
Do you have an ID? (yes/no): yes
Access granted - welcome!
Age 20 with no ID, denied. Age 15 with ID, denied. Only both together get you through - that's and. Swap it for or and only one condition needs to hold, like a discount that applies if you're a student or a senior, not both.
Nested if - A Decision Inside a Decision
A nested if is exactly what it sounds like - an if inside another if, used when the second question only makes sense once the first has already been answered YES.
username = input("Username: ")
if username == "admin":
password = input("Password: ")
if password == "kenya2025":
print("Welcome, admin!")
else:
print("Wrong password.")
else:
print("User not found.")
Username: admin
Password: kenya2025
Welcome, admin!
Notice the password question never even appears if the username is wrong - there's no point asking. That's the whole reason to reach for nested if instead of elif: elif is for the same question with different possible answers (track: DS or DE); nested if is for a question that only exists because of how the previous one was answered.
Putting It Together - NHIF Deduction Calculator
By this point everyone's used every idea from today at least once. So we close with something real - an NHIF-style deduction calculator using actual government bracket logic, simplified for learning:
print("=== NHIF DEDUCTION CALCULATOR ===")
print()
name = input("Employee name: ")
salary = int(input("Gross monthly salary (Ksh): "))
if salary < 6000:
nhif = 150
elif salary < 8000:
nhif = 300
elif salary < 12000:
nhif = 400
elif salary < 15000:
nhif = 500
elif salary < 25000:
nhif = 750
elif salary < 50000:
nhif = 850
else:
nhif = 950
net = salary - nhif
print()
print(f"Employee: {name}")
print(f"Gross: Ksh {salary:,}")
print(f"NHIF: Ksh {nhif:,}")
print(f"Net: Ksh {net:,}")
=== NHIF DEDUCTION CALCULATOR ===
Employee name: Brian Otieno
Gross monthly salary (Ksh): 35000
Employee: Brian Otieno
Gross: Ksh 35,000
NHIF: Ksh 850
Net: Ksh 34,150
Someone always asks, at this exact point, "wait - this is basically how payroll software works?" Yes. That's exactly what it is. It's just brackets and comparisons, stacked.
Try It Yourself
Easy - Matatu ticket pricing. Ask for a distance in km, then use if/elif/else to charge Ksh 30 for 0–5km, Ksh 50 for 6–15km, Ksh 80 for 16–30km, and Ksh 120 above that. Test with 3, 10, 25, and 50 km - you should get 30, 50, 80, 120.
Medium - M-Pesa daily limit checker. Ask for an account type (basic/premium) and an amount to send. Basic accounts cap at Ksh 70,000, premium at Ksh 300,000 - approve or reject based on which type and whether the amount fits the limit.
Challenge - Bank loan eligibility, using nested if. Ask if the user has a bank account. No → stop there. Yes → ask how many months they've been a customer. Under 6 months → not eligible yet. 6+ months → ask their monthly salary. Under Ksh 20,000 → doesn't qualify. Ksh 20,000+ → qualifies. Each question only appears because the one before it passed - that's the nested-if pattern in action.
What I Noticed Teaching This Round
- The
=vs==mix-up happened to almost everyone within the first ten minutes - and once it happens once, it basically never happens again - Nobody guessed correctly that elif order could silently break a grading program until I showed them Example 6 breaking live - that one lands better as a demonstration than an explanation
Next Week
Somebody's going to ask "what if I need to do this 100 times?" before I even bring it up - it happens every cohort. Loops answer that:
for i in range(5):
print(f"Student {i + 1}")
Printing five things without five print() lines is a small thing to see for the first time, but it changes how people think about repetition entirely. That's next week.
Top comments (0)