Chapter 7: If-Elif-Else Statementsยถ
๐ Open Notebookยถ
๐บ Video Tutorialยถ
If statements in Python are easy (if, elif, else) ๐ค (12:07)
๐ What Youโll Learnยถ
Make your programs smart with conditional logic! Learn how to make decisions based on different conditions.
๐ฏ Learning Objectivesยถ
Understand if, elif, and else statements
Use comparison operators (==, !=, >, <, >=, <=)
Create programs that make decisions
Chain multiple conditions together
Understand the flow of conditional execution
๐ Concept Explanationยถ
What are Conditional Statements?ยถ
Conditional statements let your program make decisions and execute different code based on whether conditions are True or False.
Syntaxยถ
Basic If Statementยถ
if condition:
# This code runs if condition is True
print("Condition is true!")
If-Else Statementยถ
if condition:
# Runs if condition is True
else:
# Runs if condition is False
If-Elif-Else Chainยถ
if condition1:
# Runs if condition1 is True
elif condition2:
# Runs if condition1 is False and condition2 is True
elif condition3:
# Runs if condition1 and condition2 are False, and condition3 is True
else:
# Runs if all conditions above are False
Comparison Operatorsยถ
Operator |
Meaning |
Example |
Result |
|---|---|---|---|
|
Equal to |
|
|
|
Not equal to |
|
|
|
Greater than |
|
|
|
Less than |
|
|
|
Greater than or equal |
|
|
|
Less than or equal |
|
|
Important: Indentation Matters!ยถ
if age >= 18:
print("Adult") # Indented - part of if block
print("Can vote") # Indented - part of if block
print("Program ends") # Not indented - always runs
๐ก Examplesยถ
Example 1: Simple If-Elseยถ
temperature = 25
if temperature > 30:
print("It's hot outside!")
else:
print("It's nice weather!")
Example 2: Multiple Conditions (Elif)ยถ
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")
Example 3: User Authenticationยถ
password = input("Enter password: ")
if password == "secret123":
print("Access granted!")
else:
print("Access denied!")
Example 4: Even or Oddยถ
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
โ๏ธ Practice Exercisesยถ
Exercise 1: Voting Eligibilityยถ
# Ask for age and determine if person can vote (18+)
age = int(input("Enter your age: "))
# Add if-else logic
Exercise 2: Grade Calculatorยถ
# Ask for a test score (0-100) and print the letter grade
# A: 90-100, B: 80-89, C: 70-79, D: 60-69, F: below 60
Exercise 3: Temperature Advisoryยถ
# Ask for temperature and give advice:
# > 30: "It's hot! Stay hydrated"
# 20-30: "Nice weather!"
# 10-19: "A bit cool, bring a jacket"
# < 10: "It's cold! Bundle up!"
Exercise 4: Login Systemยถ
# Ask for username and password
# Correct: username = "admin", password = "pass123"
# Print "Login successful" or "Invalid credentials"
Exercise 5: Movie Rating Systemยถ
# Ask for age and determine what movies they can watch
# G: All ages
# PG: 7+
# PG-13: 13+
# R: 17+
๐ Common Mistakesยถ
Mistake 1: Using = Instead of ==ยถ
# Wrong:
if age = 18: # Error! This is assignment, not comparison
print("18!")
# Correct:
if age == 18: # This is comparison
print("18!")
Mistake 2: Forgetting the Colonยถ
# Wrong:
if age > 18 # Error! Missing colon
print("Adult")
# Correct:
if age > 18: # Colon is required
print("Adult")
Mistake 3: Incorrect Indentationยถ
# Wrong:
if age > 18:
print("Adult") # Error! Not indented
# Correct:
if age > 18:
print("Adult") # Indented with 4 spaces or 1 tab
Mistake 4: Unreachable Conditionsยถ
# Wrong order:
if age > 0:
print("Positive age")
elif age > 18: # This will never execute!
print("Adult")
# Correct order (specific conditions first):
if age > 18:
print("Adult")
elif age > 0:
print("Positive age")
๐ Logical Operatorsยถ
You can combine conditions using logical operators:
AND - Both conditions must be Trueยถ
if age >= 18 and age < 65:
print("Working age")
OR - At least one condition must be Trueยถ
if age < 13 or age > 65:
print("Reduced ticket price")
NOT - Reverses the conditionยถ
if not is_raining:
print("Go outside!")
๐ฎ Real-World Examplesยถ
Example: ATM Withdrawalยถ
balance = 1000
withdrawal = int(input("Amount to withdraw: "))
if withdrawal <= 0:
print("Invalid amount")
elif withdrawal > balance:
print("Insufficient funds")
else:
balance -= withdrawal
print(f"Withdrawal successful. New balance: ${balance}")
Example: Discount Calculatorยถ
total = float(input("Enter purchase total: "))
if total >= 100:
discount = total * 0.20 # 20% off
print("20% discount applied!")
elif total >= 50:
discount = total * 0.10 # 10% off
print("10% discount applied!")
else:
discount = 0
print("No discount")
final_price = total - discount
print(f"Final price: ${final_price:.2f}")
๐ Try It Yourselfยถ
Create a number guessing game that checks if userโs guess is too high, too low, or correct
Make a BMI calculator that categorizes the result (underweight, normal, overweight, obese)
Build a simple quiz with multiple choice questions
Create a parking fee calculator based on hours parked
๐ Flow Controlยถ
Remember: In an if-elif-else chain:
Only ONE block will execute
Python checks conditions from top to bottom
Once a True condition is found, it executes that block and skips the rest
The
elseblock is optional and runs if all conditions are False
๐ Key Takeaways from Videoยถ
Use if-elif-else for conditional logic
Follow along with the video for hands-on practice
Experiment with the code examples to deepen understanding
๐ก These points cover the main concepts from the video tutorial to help reinforce your learning.
๐ Next Chapterยถ
Continue to Chapter 8: Calculator to build a functional calculator program!