21
Conditionals
Conditionals: Teaching Your Program to Make Choices
What You Might Be Wondering
"Code runs top to bottom, right? Why would it branch?"
Because the real world is full of "if X then Y, otherwise Z" scenarios. Conditionals turn business rules into executable logic.
One-Line Definition
Conditionals use if / elif / else to pick different execution paths based on boolean results.
Real-Life Analogy
A subway turnstile:
- Enough balance -> pass through
- Insufficient balance -> denied
That's your basic if/else right there.
Minimal Working Example
balance = 120
price = 99
if balance >= price:
print("Payment successful")
else:
print("Insufficient balance")
Multi-Branch Example
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "D"
print(grade)
Combining Conditions
is_member = True
order_amount = 180
if is_member and order_amount >= 100:
print("Eligible for member bulk discount")
Quick Quiz (5 min)
- Given a score, output the grade (A/B/C/D).
- Check whether "is a member AND balance > 100" is met.
- Check if a username is an empty string.
Quiz Rubric & Grading Criteria
- Direction: write runnable code that covers the core requirements and edge cases from the prompt.
- Criterion 1 (Correctness): main flow produces correct results, key branches execute.
- Criterion 2 (Readability): clear variable names, no excessive nesting.
- Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.
Take-Home Task
Write a "coupon eligibility checker" function:
- Conditions: member + minimum amount + not expired
- Output: eligible/not eligible + reason
Acceptance Criteria
You can independently:
- Write single-branch, two-branch, and multi-branch logic
- Combine
and/or/notfor business conditions - Maintain correct branch structure through proper indentation
Common Errors & Debugging Steps (Beginner Edition)
- Error message looks like gibberish: read the last line for the error type (
TypeError,NameError, etc.), then trace back to the offending line. - Not sure what a variable holds: drop a temporary
print(variable, type(variable))to check. - Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.
Common Misconceptions
-
Misconception: mixing up
=and==. -
Reality:
=assigns.==compares. -
Misconception: nesting branches deeply is fine.
-
Reality: extract complex rules into functions. Keep the main flow readable.