Chapter 8: Conditional Logic and Control Flow

This chapter introduces conditional logic and control flow.

8.1 Compare Values

Conditional logic is based on comparing values using boolean comparators:

8.2 Add Some Logic

Logical Operators

Python has three logical operators:

  • and - Both conditions must be True
  • or - At least one condition must be True
  • not - Reverses the truth value of a condition

8.3 Control the Flow of Your Program

The if Statement

if condition:
    # Code to execute if condition is True

The else Statement

if condition:
    # Code if condition is True
else:
    # Code if condition is False

The elif Statement

if condition1:
    # Code if condition1 is True
elif condition2:
    # Code if condition2 is True
else:
    # Code if neither condition is True

8.4 Challenge: Find the Factors of a Number

Problem Statement

A factor of a positive integer n is any positive integer less than or equal to n that divides n with no remainder.

def factors(n):
    for i in range(1, n + 1):
        if n % i == 0:
            print(i)

8.5 Break Out of the Pattern

break and continue Statements

  • break - Exits a loop completely
  • continue - Skips the remaining code in the current iteration and moves to the next iteration

8.6 Recover From Errors

try and except Blocks

try:
    # Code that might raise an exception
except ExceptionType:
    # Code to handle the exception

8.7 Advanced Conditional Patterns

Conditional Expressions (Ternary Operator)

Use conditional expressions for simple if-else situations in single line:

age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # adult

# Equivalent to:
if age >= 18:
    status = "adult"
else:
    status = "minor"

Nested Conditionals

Conditional statements can be nested inside each other:

age = 25
income = 45000

if age >= 18:
    if income > 50000:
        tax_rate = 0.25
        print("High income taxpayer")
    elif income > 30000:
        tax_rate = 0.20
        print("Middle income taxpayer")
    else:
        tax_rate = 0.10
        print("Low income taxpayer")
else:
    print("Too young to file taxes")
    tax_rate = 0.0

Logical Operator Precedence

Parentheses help clarify complex conditions:

score = 85
attendance = 95

# Without parentheses - and has higher precedence than or
if score > 80 and attendance > 90 or score > 90:
    print("Excellent student")

# With parentheses for clarity
if (score > 80 and attendance > 90) or score > 90:
    print("Excellent student")

8.8 Debugging Conditional Logic

Common Conditional Bugs

  • Indentation errors: Wrong indentation in if blocks
  • Assignment vs comparison: Using = instead of ==
  • Forgotten colons: Missing : after if, elif, else
  • Incorrect operator precedence: Misunderstanding and/or logic
  • Missing else: Not handling all possible cases

Debugging Techniques

# Use print statements to check conditions
x = 5
y = 10

print(f"x = {x}, y = {y}")
print(f"x > 3: {x > 3}")
print(f"y < 15: {y < 15}")
print(f"x > 3 and y < 15: {x > 3 and y < 15}")

if x > 3 and y < 15:
    print("Condition is true")
else:
    print("Condition is false")

# Test boundary values
for age in [17, 18, 19, 65, 66]:
    if age >= 18 and age <= 65:
        print(f"Age {age}: Working age")
    elif age < 18:
        print(f"Age {age}: Minor")
    else:
        print(f"Age {age}: Retirement age")

Chapter Summary

This chapter introduces conditional logic and control flow, including comparisons, logical operators, if/elif/else statements, loops, break/continue, exception handling, and advanced conditional patterns.

Mastering these concepts allows you to write programs that make decisions and handle different scenarios appropriately.

100%