Teacher's Guide
Chapter 6: Conditions
Teaching Objectives
By the end of this chapter, students should:
- Understand the concept of conditional statements
- Master the syntax and usage of
if,elif, andelsestatements - Know how to use comparison and logical operators within conditions
- Apply nested conditionals to solve more complex problems
- Understand the concept of conditional expressions (ternary operator)
Preparation
Before teaching this chapter, ensure:
- Students understand basic operators (comparison and logical)
- You have prepared examples with clear, relatable scenarios
- You have created diagrams to visualize how conditional execution works
Lesson Overview
1. Introduction to Conditional Statements (15 minutes)
Start by explaining what conditionals are and why they're important:
- Conditionals allow programs to make decisions based on certain conditions
- They enable different code paths to execute depending on whether conditions are true or false
- They are fundamental to programming logic and problem-solving
Analogy: Conditionals are like crossroads in a journey - based on specific conditions, you choose which path to take.
Real-world examples:
- Checking the weather to decide what to wear
- Deciding whether to bring an umbrella based on the forecast
- Checking if you have enough money before buying something
2. Basic If Statements (20 minutes)
Introduce the basic structure of an if statement:
# Basic if statement
age = 15
if age >= 13:
print("You can watch a PG-13 movie")
# Another example
temperature = 28
if temperature > 25:
print("It's hot today!")
print("Remember to drink water")
Explain the components:
- The
ifkeyword begins the conditional block - The condition (
age >= 13ortemperature > 25) evaluates to eitherTrueorFalse - The indented block runs only if the condition is
True - Multiple statements can be included in the indented block
Teaching points:
- Emphasize the importance of proper indentation
- Show how the condition must evaluate to a boolean value
- Demonstrate how to use comparison operators in conditions
3. If-Else Statements (15 minutes)
Expand to include the else clause:
# If-else example
age = 10
if age >= 13:
print("You can watch a PG-13 movie")
else:
print("Sorry, this movie is not suitable for your age")
# Another example
has_ticket = True
if has_ticket:
print("Welcome to the concert!")
else:
print("You need to purchase a ticket first")
Teaching approach:
- Explain that the
elseblock executes when the condition isFalse - Use flowcharts to visually represent the decision paths
- Demonstrate that exactly one of the blocks will always execute
4. If-Elif-Else Statements (20 minutes)
Introduce multiple conditions with elif:
# Grade example
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")
# Weather example
weather = "cloudy"
if weather == "sunny":
print("Wear sunglasses")
elif weather == "rainy":
print("Bring an umbrella")
elif weather == "snowy":
print("Wear a warm coat")
elif weather == "cloudy":
print("You might want a light jacket")
else:
print("Check the weather forecast")
Teaching points:
- Explain that
elifis short for "else if" - Conditions are checked in order, and the first true condition has its block executed
- Once a condition is met, the remaining conditions are skipped
- The
elseblock is optional and runs only if all conditions areFalse
5. Nested Conditionals (15 minutes)
Show how conditionals can be placed inside other conditionals:
# Nested if example
age = 15
has_permission = True
if age >= 13:
if has_permission:
print("You can play the game")
else:
print("You need parental permission")
else:
print("You are too young for this game")
# Ticket pricing example
age = 65
is_student = False
if age < 18:
print("Child ticket: $5")
else:
if age >= 65:
print("Senior ticket: $8")
else:
if is_student:
print("Student ticket: $8")
else:
print("Adult ticket: $10")
Teaching approach:
- Use indentation to clearly show the nesting structure
- Explain that each level of nesting represents a further refinement of conditions
- Show how nested conditions can often be rewritten using logical operators
# Rewriting the nested condition with logical operators
if age >= 13 and has_permission:
print("You can play the game")
elif age >= 13: # and not has_permission
print("You need parental permission")
else:
print("You are too young for this game")
6. Using Logical Operators in Conditions (15 minutes)
Demonstrate combining conditions with logical operators:
# Using 'and' operator
age = 25
income = 50000
if age > 21 and income > 40000:
print("You qualify for the premium credit card")
else:
print("You do not qualify for the premium credit card")
# Using 'or' operator
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("The store is open from 10 AM to 6 PM")
else:
print("The store is open from 9 AM to 9 PM")
# Using 'not' operator
is_raining = False
if not is_raining:
print("You can go for a walk")
else:
print("Better stay indoors")
Teaching tips:
- Review truth tables for logical operators
- Explain the short-circuit evaluation of logical operators
- Show how to use parentheses to clarify complex conditions
# Complex condition with parentheses
if (age > 18 and income > 30000) or has_guarantor:
print("Loan approved")
else:
print("Loan denied")
7. Conditional Expressions (Ternary Operator) (10 minutes)
Introduce the conditional expression syntax for simple conditions:
# Traditional if-else
age = 20
if age >= 18:
status = "adult"
else:
status = "minor"
# Same logic using conditional expression
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # Outputs: adult
# Another example
num = -5
absolute = num if num >= 0 else -num
print(absolute) # Outputs: 5
Teaching approach:
- Explain that this is a more compact way to write simple if-else statements
- Emphasize that it should only be used for simple conditions to maintain readability
- Show the general syntax:
value_if_true if condition else value_if_false
8. Guided Practice (20 minutes)
Have students work through these exercises:
-
Movie ticket prices:
# Determine ticket price based on age age = int(input("Enter your age: ")) if age < 5: price = 0 elif age < 13: price = 8 elif age < 65: price = 12 else: price = 10 print(f"Your ticket costs ${price}") -
Simple calculator:
# Basic calculator with error handling num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) operation = input("Enter operation (+, -, *, /): ") if operation == "+": result = num1 + num2 elif operation == "-": result = num1 - num2 elif operation == "*": result = num1 * num2 elif operation == "/": if num2 == 0: print("Error: Cannot divide by zero") else: result = num1 / num2 else: print("Invalid operation") result = None if result is not None: print(f"Result: {result}")
9. Problem-Solving Activities (15 minutes)
Present students with more challenging problems:
-
Leap year checker:
# Check if a year is a leap year year = int(input("Enter a year: ")) if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print(f"{year} is a leap year") else: print(f"{year} is not a leap year") -
BMI calculator:
# Calculate BMI and determine category weight = float(input("Enter weight in kg: ")) height = float(input("Enter height in meters: ")) bmi = weight / (height ** 2) print(f"Your BMI is: {bmi:.1f}") if bmi < 18.5: category = "Underweight" elif bmi < 25: category = "Normal weight" elif bmi < 30: category = "Overweight" else: category = "Obese" print(f"Category: {category}")
10. Review and Discussion (10 minutes)
- Review the key concepts covered
- Ask students to explain in their own words:
- What is a conditional statement?
- When would you use
elifversus multipleifstatements? - How do logical operators help with conditions?
Common Challenges and Solutions
- Indentation errors: Emphasize the importance of consistent indentation in Python.
- Condition confusion: Help students understand the difference between
=(assignment) and==(comparison). - Logical operator misconceptions: Review logical operator precedence and short-circuit evaluation.
- Nested conditionals complexity: Encourage students to refactor nested conditionals when possible for readability.
Extension Activities
For students who finish early:
- Challenge them to create a rock-paper-scissors game using conditionals
- Have them build a simple quiz program with score tracking
- Ask them to implement a password strength checker with multiple criteria
Assessment
Look for these indicators of understanding:
- Students can write syntactically correct conditional statements
- They can create programs that make appropriate decisions based on inputs
- They understand how to combine conditions using logical operators
- They can trace the execution path of code with conditionals