> Source URL: /demos/cs1-path/lectures/lecture-02.slides
---
lecture_number: 2
title: Control Flow
outcomes: [2]
date: Week 2
---

# 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.

```python
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**:

```python
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:

| Operator | Meaning               | Example            |
| -------- | --------------------- | ------------------ |
| `==`     | Equal to              | `5 == 5` → `True`  |
| `!=`     | Not equal to          | `5 != 3` → `True`  |
| `<`      | Less than             | `3 < 5` → `True`   |
| `>`      | Greater than          | `5 > 3` → `True`   |
| `<=`     | Less than or equal    | `5 <= 5` → `True`  |
| `>=`     | Greater than or equal | `3 >= 5` → `False` |

---

## Common Mistake: = vs ==

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

```python
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:

```python
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`:

```python
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:

```python
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:

```python
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`:

```python
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:

```python
age = 25
has_license = True

if age >= 16 and has_license:
    print("You can drive!")
```

| `age >= 16` | `has_license` | Result   |
| ----------- | ------------- | -------- |
| True        | True          | **True** |
| True        | False         | False    |
| False       | True          | False    |
| False       | False         | False    |

---

## Combining Conditions: or

At least one condition must be True:

```python
is_weekend = False
is_holiday = True

if is_weekend or is_holiday:
    print("No class today!")
```

| `is_weekend` | `is_holiday` | Result   |
| ------------ | ------------ | -------- |
| True         | True         | **True** |
| True         | False        | **True** |
| False        | True         | **True** |
| False        | False        | False    |

---

## Negation: not

Flips True to False and vice versa:

```python
is_raining = False

if not is_raining:
    print("Leave the umbrella home!")
```

| `is_raining` | `not is_raining` |
| ------------ | ---------------- |
| True         | False            |
| False        | **True**         |

---

## Nested Conditionals

You can put `if` statements inside other `if` statements:

```python
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`:

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

---

## Comparing Strings

Works just like numbers:

```python
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:**

```python
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:**

```python
grade = 85

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

This is Python shorthand for:

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

---

## Common Mistakes

**Forgetting the colon:**

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

**Wrong indentation:**

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

**Using = instead of ==:**

```python
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](../labs/lab-02.spec.md), you'll:

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

---

## Questions?


---

## Backlinks

The following sources link to this document:

- [Lecture 2: Control Flow](/demos/cs1-path/index.path.llm.md)
- [Lecture 2: Control Flow](/demos/cs1-path/labs/lab-02.spec.llm.md)
- [Lecture 2: Control Flow](/demos/cs1-path/course.schedule.llm.md)
