lesson
45 min

Decisions and Loops

Use if/else to make decisions and for loops to repeat work across a list of readings.

Objective

By the end of this lesson, you can store data in a list, loop over it, and count values that meet a condition.

Lists

A list holds many values in order, inside square brackets.

highs = [88, 93, 101, 97, 85, 102, 99]

These are seven made-up daily high temperatures for one week. highs[0] is the first value (88). Python counts from zero.

Decisions with if, elif, else

An if statement runs code only when a condition is true. elif means "else if."

temp = 101
if temp >= 100:
    print("Extreme heat")
elif temp >= 90:
    print("Hot")
else:
    print("Mild")

The indent (four spaces) shows which lines belong to each branch. Python cares about indents.

Loops

A for loop runs the same code once for each item in a list. Put a loop and a decision together, and you can summarize data.

Run it. Then add a new reading of 104 to the list and run it again. How do the totals change?
Python 3
Ctrl+Enter to run | Tab to indent | Python runs in your browser via Pyodide

sum() adds a list. len() counts its items. Average equals sum divided by count.

A national example

Judgment check

Counting "hot days" sounds neutral. But the threshold you pick changes who gets help. A cutoff that fits one region may leave people in another region unprotected. When your code turns a number into an action, ask who chose the cutoff and why.

Reflection

Private. Saved only in this browser. No one else can see it.

Ask. Answer. Build together.