Conditional Statements
# Conditional Statements
Welcome to Chapter 7! Conditional statements give your programs the power to make decisions. Based on conditions, your code can take different paths — just like you decide whether to carry an umbrella based on the weather.
---
1. Introduction
In real life, you make decisions constantly: *"If it's raining, take an umbrella. Otherwise, wear sunglasses."* Programming works the same way. Conditional statements evaluate a condition (True or False) and execute different code blocks accordingly.
---
2. Learning Objectives
-
Write
if,if-else, andif-elif-elsestatements.
- Use nested conditionals.
- Apply the ternary operator.
- Use match-case (Python 3.10+).
- Build a grade calculator project.
---
3. The if Statement
```python id="py7_ex1" age = 18
if age >= 18: print("You are an adult! ✅") print("You can vote.")
# If condition is False, the block is skipped temperature = 15 if temperature > 30: print("It's hot!") # This won't execute
if Statement Flow: ┌──────────┐ │ Condition │ └────┬─────┘ │ ┌─────┴─────┐ │ True? │ False? ▼ ▼ ┌─────────┐ (skip) │ Execute │ │ block │ └─────────┘
python id="py7_ex2" score = 45
if score >= 50: print("PASSED ✅") else: print("FAILED ❌")
python id="py7_ex3" number = int(input("Enter a number: "))
if number % 2 == 0: print(f"{number} is EVEN") else: print(f"{number} is ODD")
python id="py7_ex4" score = 78
if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F"
print(f"Score: {score} → Grade: {grade}")
elif Ladder Flow: ┌──────────────┐ │ score >= 90? │──Yes──→ Grade A └──────┬───────┘ No ┌──────────────┐ │ score >= 80? │──Yes──→ Grade B └──────┬───────┘ No ┌──────────────┐ │ score >= 70? │──Yes──→ Grade C └──────┬───────┘ No ┌──────────────┐ │ score >= 60? │──Yes──→ Grade D └──────┬───────┘ No └──────────────→ Grade F
python id="py7_ex5" age = 25 has_id = True
if age >= 18: if has_id: print("Access granted! ✅") else: print("Please bring your ID. 🪪") else: print("Sorry, you must be 18+. ❌")
python id="py7_ex6" age = 20 status = "Adult" if age >= 18 else "Minor" print(status) # Adult
# Nested ternary (use sparingly!) score = 85 grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F" print(f"Grade: {grade}") # B
python id="py7_ex7" command = "start"
match command: case "start": print("Starting the system... 🟢") case "stop": print("Stopping the system... 🔴") case "restart": print("Restarting... 🔄") case _: print("Unknown command! ❓")
python id="py7_ex8" # Falsy values: False, 0, 0.0, "", [], {}, (), None # Everything else is Truthy
name = "" if name: print(f"Hello, {name}!") else: print("Name is empty!") # This runs
items = [1, 2, 3] if items: print(f"List has {len(items)} items") # This runs
python id="py7_project" print("=" * 45) print(" 📊 STUDENT GRADE CALCULATOR") print("=" * 45)
name = input(" Student Name: ") math_score = float(input(" Math Score (0-100): ")) science_score = float(input(" Science Score (0-100): ")) english_score = float(input(" English Score (0-100): "))
average = (math_score + science_score + english_score) / 3
if average >= 90: grade, remark = "A+", "Outstanding! 🌟" elif average >= 80: grade, remark = "A", "Excellent! 🎉" elif average >= 70: grade, remark = "B", "Good Job! 👍" elif average >= 60: grade, remark = "C", "Satisfactory 📝" elif average >= 50: grade, remark = "D", "Needs Improvement ⚠️" else: grade, remark = "F", "Failed ❌"
print("\n" + "=" * 45)
print(f"{'REPORT CARD':^45}")
print("=" * 45)
print(f" {'Student':<15}: {name}")
print(f" {'Math':<15}: {math_score}")
print(f" {'Science':<15}: {science_score}")
print(f" {'English':<15}: {english_score}")
print(f" {'Average':<15}: {average:.1f}")
print(f" {'Grade':<15}: {grade}")
print(f" {'Remark':<15}: {remark}")
print(f" {'Status':<15}: {'PASSED ✅' if average >= 50 else 'FAILED ❌'}")
print("=" * 45)
``
---
11. Common Mistakes
-
1.
Using =
instead of==:if x = 5is assignment, not comparison.
-
2.
Forgetting the colon: if x > 5
needs a:at the end.
- 3. Wrong indentation: All code in an if-block must be indented equally.
-
4.
Overly complex nesting: Flatten with elif
or early returns.
---
12. Best Practices
-
Use elif
instead of nestedifwhen possible.
- Keep conditions simple and readable.
-
Use truthy/falsy checks: if items:
instead ofif len(items) > 0:.
- Use the ternary operator for simple assignments.
---
13. Exercises
- 1. Write a program that checks if a number is positive, negative, or zero.
- 2. Build a leap year checker.
- 3. Create a ticket pricing system based on age.
- 4. Write a program that finds the largest of three numbers.
- 5. Build a simple login system with username and password check.
---
14. MCQs with Answers
Q1: What keyword handles multiple conditions? A) else if B) elif C) elseif D) elsif Answer: B
Q2: What does the ternary operator look like?
A) x ? y : z B) y if x else z C) x then y else z D) if x: y else: z
Answer: B
Q3: Which value is falsy? A) 1 B) "hello" C) [] D) True Answer: C — Empty list is falsy.
Q4: What ends an if statement header? A) Semicolon B) Colon C) Parenthesis D) Curly brace Answer: B
Q5: match-case was introduced in Python:
A) 3.8 B) 3.9 C) 3.10 D) 3.11
Answer: C
Q6: What is the _ in match-case?
A) Error handler B) Wildcard/default C) Break D) Continue
Answer: B
Q7: Can elif exist without if? A) Yes B) No Answer: B
Q8: if 0: evaluates to:
A) True B) False C) Error D) None
Answer: B — 0 is falsy.
Q9: Can we have if without else? A) Yes B) No Answer: A
Q10: What does not True return?
A) True B) False C) None D) Error
Answer: B
---
15. Interview Questions
-
1.
What are truthy and falsy values? Falsy: False, 0, 0.0, "", [], {}, (), None
. All others are truthy.
- 2. Difference between if-elif and multiple if statements? elif stops at first True; multiple ifs check all conditions independently.
- 3. What is match-case in Python? Structural pattern matching (3.10+), similar to switch-case but more powerful with pattern matching.
- 4. Can conditions have side effects? Yes, but it's generally discouraged for readability.
-
5.
What is short-circuit evaluation in conditionals? Python stops evaluating and
/oras soon as result is determined.
---
16. Summary
-
if
executes code when condition is True.
-
elif
handles multiple conditions sequentially.
-
else
catches everything not matched by if/elif.
-
Ternary operator: value_if_true if condition else value_if_false
.
-
match-case
(3.10+) provides structural pattern matching.
- Use truthy/falsy values for cleaner conditions.
---
17. Next Chapter Recommendation
In Chapter 8: Loops in Python, you'll learn to repeat code with for and while` loops, and build a number guessing game! 🚀