Block 3: if/else and Conditionals
Control program flow with if/elif/else.
Concepts
- if/elif/else syntax and indentation
- Comparison operators: ==, !=, <, >, <=, >=
- Logical operators: and, or, not
- Nested conditionals
Code Examples
Basic if/elif/else
score = 85
if score >= 90:
print('A')
elif score >= 80:
print('B')
else:
print('C or below')
Logical operators
age = 25
has_ticket = True
if age >= 18 and has_ticket:
print('Entry allowed')
if age < 13 or age > 65:
print('Eligible for discount')
Exercise
Write a BMI category classifier (underweight, normal, overweight, obese). Given a score (0–100), print the letter grade A/B/C/D/F.
Solution
def bmi_category(bmi):
if bmi < 18.5: return 'underweight'
elif bmi < 25: return 'normal'
elif bmi < 30: return 'overweight'
else: return 'obese'
def letter_grade(score):
if score >= 90: return 'A'
elif score >= 80: return 'B'
elif score >= 70: return 'C'
elif score >= 60: return 'D'
else: return 'F'
print(bmi_category(22)) # normal
print(letter_grade(85)) # BPractice Problems
Problem 1: Write a function that returns 'even' or 'odd' for any integer.
Hint: Use % 2
Problem 2: Given age, print 'minor' if <18, 'adult' if 18-64, 'senior' otherwise.
Hint: Use elif chain
Application
Conditionals are used everywhere: filtering data, validating inputs, branching in ML pipelines, and business logic.
Case Study
An e-commerce site uses conditionals: if cart_total > 100 and is_member: apply 10% discount. Nested conditions handle complex rules.
Homework
Explain why indentation matters in Python. Write an example that would break without correct indentation.