Lecture 2: Control Flow

Overview

Today we'll learn how to make programs that make decisions.

The Story So Far

Programs we've written execute top to bottom, every line, every time.

name = input("Name: ")
print("Hello,", name)
# Always prints, no matter what

But what if we want different behavior in different situations?

Making Decisions

Real programs need to respond to different conditions:

  • "If the password is correct, log in"
  • "If the temperature is below freezing, show a warning"
  • "If the grade is above 90, assign an A"

This is called control flow—controlling which code runs.

Boolean Values

Before we make decisions, we need True and False:

is_raining = True
is_sunny = False

print(is_raining)  # True
print(type(True))  # <class 'bool'>

Named after mathematician George Boole.

Comparison Operators

Create boolean values by comparing things:

OperatorMeaningExample
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than3 < 5True
>Greater than5 > 3True
<=Less than or equal5 <= 5True
>=Greater than or equal3 >= 5False

Common Mistake: = vs ==

= is assignment (storing a value) == is comparison (checking equality)

x = 5      # Assigns 5 to x
x == 5     # Checks if x equals 5 (True)
x == 3     # Checks if x equals 3 (False)

This is a very common source of bugs!

The if Statement

Run code only when a condition is True:

temperature = 75

if temperature > 70:
    print("It's warm outside!")

If temperature > 70 is True, the indented code runs. If False, Python skips it.

Indentation Matters!

Python uses indentation to know what's inside the if:

temperature = 75

if temperature > 70:
    print("It's warm!")      # Inside the if
    print("Wear shorts!")    # Also inside

print("Have a nice day!")    # Outside - always runs

Use 4 spaces for each level of indentation.

if-else

Do one thing or another:

temperature = 65

if temperature > 70:
    print("It's warm!")
else:
    print("It's cool!")

Exactly one of these will run—never both, never neither.

Multiple Conditions: elif

Check several conditions in order:

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print("Your grade:", grade)

How elif Works

Python checks conditions top to bottom and stops at the first True:

score = 85

if score >= 90:    # False, skip
    grade = "A"
elif score >= 80:  # True! Run this, then done
    grade = "B"
elif score >= 70:  # Never checked
    grade = "C"
# ...

Order matters!

Combining Conditions: and

Both conditions must be True:

age = 25
has_license = True

if age >= 16 and has_license:
    print("You can drive!")
age >= 16has_licenseResult
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse

Combining Conditions: or

At least one condition must be True:

is_weekend = False
is_holiday = True

if is_weekend or is_holiday:
    print("No class today!")
is_weekendis_holidayResult
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Negation: not

Flips True to False and vice versa:

is_raining = False

if not is_raining:
    print("Leave the umbrella home!")
is_rainingnot is_raining
TrueFalse
FalseTrue

Nested Conditionals

You can put if statements inside other if statements:

has_ticket = True
age = 15

if has_ticket:
    if age >= 18:
        print("Welcome to the R-rated movie!")
    else:
        print("Sorry, you need to be 18+")
else:
    print("Please buy a ticket first")

But often you can simplify with and:

if has_ticket and age >= 18:
    print("Welcome!")

Comparing Strings

Works just like numbers:

password = input("Enter password: ")

if password == "secret123":
    print("Access granted!")
else:
    print("Wrong password!")

String comparison is case-sensitive:

  • "Hello" == "hello"False
  • "Hello" == "Hello"True

Common Patterns

Validating input:

age = int(input("Enter age: "))

if age < 0:
    print("Age can't be negative!")
elif age > 150:
    print("That seems unlikely...")
else:
    print("Your age is", age)

Common Patterns

Checking ranges:

grade = 85

if 80 <= grade <= 89:
    print("That's a B!")

This is Python shorthand for:

if grade >= 80 and grade <= 89:
    print("That's a B!")

Common Mistakes

Forgetting the colon:

if temperature > 70   # Error! Missing :
    print("Warm!")

Wrong indentation:

if temperature > 70:
print("Warm!")  # Error! Must be indented

Using = instead of ==:

if password = "secret":  # Error! Use ==
    print("Correct!")

Key Takeaways

  1. Booleans are True or False
  2. Comparison operators: ==, !=, <, >, <=, >=
  3. if runs code when condition is True
  4. elif checks additional conditions
  5. else runs when all conditions are False
  6. and, or, not combine conditions
  7. Indentation defines what's inside the if

Lab Preview

In Lab 2, you'll:

  • Practice with boolean expressions
  • Build programs that make decisions
  • Create a number guessing game
  • Combine conditions with and/or