Day 3: Conditional Statements & Boolean Logic

🐍 Day 3: Conditional Statements & Boolean Logic


1. Learning Objectives

By the end of Day 3, you will be able to:

  • Control the flow of your program using if, elif, and else
  • Build complex conditions with Boolean logic (and, or, not)
  • Nest conditions inside one another for multi-layered decisions
  • Write compact conditional expressions using the ternary operator
  • Avoid common pitfalls like indentation errors and dangling else

2. Concept Explanation

2.1 Why Conditionals? — Making Decisions

So far, your programs have run from top to bottom, executing every line. But real programs need to branch — do different things depending on the situation.

          
If it's raining: bring an umbrella Otherwise: wear sunglasses

Python gives you the tools to express exactly that kind of logic.


2.2 The if Statement

The simplest decision: execute a block of code only when a condition is True.

          
temperature = 30 if temperature > 25: print("It's a hot day!") print("Drink plenty of water.") print("Program continues here...")

Rules:

  • The condition (temperature > 25) must be a Boolean expression (or something that can be treated as Boolean).
  • The indented block (4 spaces is standard) belongs to the if.
  • After the indented block, the program returns to normal execution.

Output (when temperature = 30):

          
It's a hot day! Drink plenty of water. Program continues here...

Output (when temperature = 20):

          
Program continues here...

2.3 The else Clause

When the if condition is False, you can provide an alternative path.

          
is_raining = False if is_raining: print("Bring an umbrella") else: print("Wear sunglasses") print("Done!")

⚠️ Indentation matters. The if and else must have exactly the same indentation level. Their code blocks must also be consistently indented (usually 4 spaces).


2.4 The elif — Multiple Branches

For more than two paths, use elif (short for "else if").

          
score = 82 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")

How Python evaluates an if-elif-else chain:

  1. Check the if condition.
  2. If it's True, execute its block and skip the rest.
  3. If False, check the first elif.
  4. Continue down the chain until a condition is True or you hit else.

💡 Only the first true branch runs. Order matters! If you put >= 60 before >= 90, the A grade would never be reached.


2.5 Nesting Conditions

You can put if statements inside other if statements for hierarchical decisions.

          
age = 20 has_id = True if age >= 18: print("Age requirement met.") if has_id: print("Entry granted. Welcome!") else: print("Please bring your ID.") else: print("Too young to enter.")

Style tip: Avoid excessive nesting (more than 3 levels deep) — it becomes hard to read. Often you can combine conditions with and/or instead.


2.6 Ternary Operator — One-Line if/else

For simple value assignment based on a condition, Python offers the ternary operator (conditional expression):

          
# Traditional if score >= 60: status = "pass" else: status = "fail" # Ternary (one-liner) status = "pass" if score >= 60 else "fail"

Syntax: value_if_true if condition else value_if_false

More examples:

          
num = 7 parity = "even" if num % 2 == 0 else "odd" max_val = a if a > b else b # Like a built-in max function

Use it sparingly — readability first. If the logic is complex, stick to regular if-else.


2.7 Boolean Logic Revisited

Since conditionals rely on Boolean expressions, let's reinforce what you learned on Day 2.

Truthiness recap:

          
# "Falsy" values (treated as False in an if condition) bool(0) # False bool("") # False bool([]) # False bool(None) # False # Everything else is "truthy" bool(42) # True bool("hello") # True

So you can write:

          
name = input("Your name: ") if name: print(f"Hello, {name}!") else: print("You didn't enter a name.")

Short-circuit evaluation:

Python evaluates logical expressions left-to-right and stops as soon as the outcome is determined.

          
# If x > 0 is False, the second part is never checked (avoids division by zero) x = 0 if x > 0 and (10 / x > 5): print("Condition met") else: print("Safe -- no division by zero!")

Because x > 0 is False, the and expression immediately is False, so Python doesn't execute 10 / x. This can be used intentionally to guard against errors.


2.8 Common Mistakes & Debugging

Mistake Example Why it happens
Using = instead of == if x = 5: = assigns, == compares. Python raises a syntax error.
Mismatched indentation if x > 0:\n print("positive") # missing indentation IndentationError: expected an indented block
Forgetting colon : if x > 0 \n print("ok") SyntaxError: expected ':'
Putting elif after else if ... else ... elif ... elif must come before else
Overly complex if/else chains Many nested conditions Consider restructuring or using functions (Day 5).

Debugging tip: If your condition isn't doing what you expect, print the values right before the if:

          
print(f"score: {score}, type: {type(score)}") if score >= 60: ...

Often the issue is an unexpected type or value.


3. Code Examples

Example 1: Simple Login Check

          
# A mock login system using conditionals stored_password = "python123" user_input = input("Enter your password: ") if user_input == stored_password: print("Access granted. Welcome back!") else: print("Access denied. Wrong password.")

Example 2: Age Group Classifier

          
age = int(input("Please enter your age: ")) if age < 0: print("Invalid age") elif age < 13: print("Child") elif age < 20: print("Teenager") elif age < 65: print("Adult") else: print("Senior")

Example 3: Ternary + Nesting

          
# Determine shipping cost based on membership and order total is_member = True order_total = 75.0 # Nested conditional with ternary shipping = 0.0 if is_member: shipping = 0.0 if order_total >= 50 else 5.99 else: shipping = 4.99 if order_total >= 100 else 9.99 print(f"Shipping cost: ${shipping:.2f}")

4. Hands-On Exercises

Exercise 1: Even or Odd (with message)

Ask the user for an integer. Print "Even" if it's even, "Odd" if it's odd. (Use %)

Exercise 2: Leap Year Checker

Ask for a year. A leap year is divisible by 4, but not by 100, unless also divisible by 400. Print "Leap year" or "Not a leap year".

Exercise 3: Maximum of Three

Ask the user for three numbers. Print the largest one using only if, elif, else (no built-in max()).

Exercise 4: Vowel or Consonant

Ask for a single letter. Print whether it's a vowel (a, e, i, o, u) or a consonant. Handle both uppercase and lowercase input. (Hint: convert input to lowercase with .lower())

Exercise 5: Simple Calculator

Ask for two numbers and an operator (+, -, *, /). Perform the correct arithmetic and print the result. If the operator is not recognised, print an error message.


5. Applied Challenge Task 🏗️

Movie Ticket Pricing System

Build a program that calculates the ticket price based on these rules:

  • Base price: $12
  • Age discount: Children (under 13) get 50% off, Seniors (65+) get 30% off
  • Day discount: On Tuesday, everyone gets an additional $2 off
  • Member discount: Members get an additional 15% off the already discounted price

Your program should:

  1. Ask for the customer's age
  2. Ask for the day of the week (e.g., "Tuesday")
  3. Ask if they are a member (yes/no)
  4. Apply discounts in the order described above
  5. Print a ticket receipt:
          
=== TICKET RECEIPT === Base Price: $12.00 Age Discount: -$6.00 Tuesday Deal: -$2.00 Member Discount: -$0.60 Final Price: $3.40 ======================

Stretch goals:

  • Ensure the final price never goes below $0
  • Add a student discount (show ID? → 10% off)
  • Format all dollar amounts to 2 decimal places

6. Brief Review Summary

Concept Key Points
if Executes block when condition is True
elif Additional conditions checked only if previous were False
else Default block when no condition was True
Nesting if inside if — use sparingly
Ternary x = a if cond else b — compact assignment
Boolean logic and, or, not — short-circuit evaluation
Indentation 4 spaces per level; consistent throughout file
Common errors = vs ==, missing colon, wrong indentation

7. Preview of Next Topic — Day 4

Tomorrow we'll make programs that repeat themselves:

  • for loops — iterating over sequences
  • while loops — repeating while a condition is True
  • Loop controlbreak, continue, and else with loops
  • Avoiding infinite loops

🎯 Your Action Items for Day 3:

  1. ✅ Complete all 5 exercises
  2. ✅ Complete the Movie Ticket Pricing challenge
  3. ✅ Experiment with edge cases (empty input, negative numbers)
  4. ✅ Try rewriting some of your Day 2 code using conditionals


Comments

Popular posts from this blog

Day 1: Welcome to Python — Your Journey Begins

Python: Your Gateway to Coding Adventures

Day 11: List Comprehensions & Lambda Functions

Earn From the Comfort of Your Home

Build the skills to work comfortably from home, on your own terms.

Get Started Today