← Python

Python from zero · Part 2 of 6 · No experience needed

The full story · about 13 minutes

Python from zero, part 2: decisions and repeats

1 · Observe

Real work is deciding and repeating

Words used in this lesson
WordWhat it means
ConditionA question whose answer is True or False, such as price <= 70.
if / elif / elseIf the condition is true do this, else if another is true do that, otherwise do the last thing.
IndentationThe spaces at the start of a line. In Python they are part of the meaning.
ListAn ordered collection of values in square brackets: [62.5, 48.0, 71.2].
IndexA value's position in a list. Counting starts at 0.
LoopRepeating the same steps for each value.
AccumulatorA name you update inside a loop to build a total or a count.

You are shortlisting flats. For each one you ask: is it within budget? If yes, keep it. If not, skip it. That is a decision (if) repeated over a collection (for). Nearly every data task is built from these two moves.

Everyday words and Python words
You sayPython writesMeaning
If the price is within budgetif price <= budget:Do the next, indented, lines only when True
Otherwiseelse:Do these lines when the condition was False
For each flat in my listfor price in prices:Run the indented lines once per value
Keep a running totaltotal = total + priceStore the old total plus this price

2 · Express

The shape of if and for

Both start with a line ending in a colon. The lines that belong to it are indented by the same number of spaces (four is standard). The block ends when the indentation stops.

if condition:
lines that run only when it is True
else:
lines that run when it is False
The colon opens the block. The indentation shows what is inside it.
for name in collection:
lines that run once for each value, with name holding that value
Joining questions
WordMeansExampleAnswer when price = 62.5
andboth must be Trueprice > 50 and price < 70True
orat least one is Trueprice < 50 or price > 100False
notflips the answernot price > 100True

A list stores values in order. The first value is at position 0, not 1, because the position is how far from the start you are. A list of four values has positions 0, 1, 2 and 3. len(list) tells you how many values there are.

Check yourself

A list has five values. What is the position of the last one?

3 · Visualize

Trace a loop, one pass at a time

A loop runs its block once per value. Trace it just as you traced the lines in part 1. Here the budget is 60 and the list is [62.5, 48.0, 71.2].

Tracing the shortlist loop
Passpriceprice <= 60?shortlist afterwards
Start[]
162.5False, so skip[]
248.0True, so keep[48.0]
371.2False, so skip[48.0]
End[48.0]

4 · Discover

Try each piece

First a decision. Change price_lakh to 40, then to 62.5, then to 90, and predict which message appears before you run it.

if, elif and else: pick one path
price_lakh = 62.5
budget_lakh = 70

if price_lakh <= 50:
    print("cheap: shortlist it")
elif price_lakh <= budget_lakh:
    print("within budget: visit it")
else:
    print("too expensive: skip it")
within budget: visit it
Edit and run this code in your browser

Live Python

if, elif and else: pick one path

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Only one branch runs. Python checks the conditions from the top and takes the first that is True. Now a list, and counting from zero.

A list holds many values, counted from zero
prices = [62.5, 48.0, 71.2, 55.5]
print(len(prices))        # how many values
print(prices[0])          # the first one: counting starts at 0
print(prices[3])          # the last one
print(prices[-1])         # negative counts from the end
prices.append(80.0)       # add one at the end
print(prices)
print(48.0 in prices)     # is it in the list?
4
62.5
55.5
55.5
[62.5, 48.0, 71.2, 55.5, 80.0]
True
Edit and run this code in your browser

Live Python

A list holds many values, counted from zero

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Now a loop with a decision inside it. This is the shortlist trace from the table, made real.

for: do the same thing to every value
prices = [62.5, 48.0, 71.2, 55.5]
budget = 60
shortlist = []
for price in prices:          # price takes each value in turn
    if price <= budget:
        shortlist.append(price)
print("shortlist:", shortlist)
print("how many:", len(shortlist))
shortlist: [48.0, 55.5]
how many: 2
Edit and run this code in your browser

Live Python

for: do the same thing to every value

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

The loop from the table, run for real
prices = [62.5, 48.0, 71.2]
shortlist = []
for price in prices:
    keep = price <= 60
    print(price, "<= 60?", keep)
    if keep:
        shortlist.append(price)
print(shortlist)
62.5 <= 60? False
48.0 <= 60? True
71.2 <= 60? False
[48.0]
Edit and run this code in your browser

Live Python

The loop from the table, run for real

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

5 · Apply

Two worked examples

Example 1, a running total. Start total at 0. On every pass, store the old total plus the current price. After the loop, divide by how many values there were to get the average.

A running total (the accumulator pattern)
prices = [62.5, 48.0, 71.2, 55.5]
total = 0
for price in prices:
    total = total + price     # store the old total plus this price
print("total:", total)
print("average:", round(total / len(prices), 2))
print("same answer with sum():", sum(prices) / len(prices))
total: 237.2
average: 59.3
same answer with sum(): 59.3
Edit and run this code in your browser

Live Python

A running total (the accumulator pattern)

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

The four prices add to 237.2, so the average is 59.3. Python also has sum(), which does the same job in one step. Writing the loop once teaches you what sum() does.

Example 2 is counting: start a count at 0 and add 1 each time a condition is True. This is how you would count missing values in a column.

Counting with a condition
areas = [1075, None, 900, None, 1200]    # None means the value is missing
missing = 0
for area in areas:
    if area is None:
        missing = missing + 1
print("missing values:", missing, "out of", len(areas))
missing values: 2 out of 5
Edit and run this code in your browser

Live Python

Counting with a condition

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Check yourself

In for price in prices: what does price hold on the second pass?

6 · Where it goes wrong

Four classic slips

What Python says when these go wrong
try:
    compile("if 5 > 3\n    pass", "<cell>", "exec")        # forgot the colon
except SyntaxError as e:
    print("SyntaxError:", e.msg)
try:
    compile("for n in [1, 2]:\nprint(n)", "<cell>", "exec")  # forgot to indent
except SyntaxError as e:
    print(type(e).__name__ + ":", e.msg)
prices = [62.5, 48.0, 71.2]
try:
    print(prices[3])           # there are only three values: positions 0, 1, 2
except IndexError as e:
    print("IndexError:", e)
SyntaxError: expected ':'
IndentationError: expected an indented block after 'for' statement on line 1
IndexError: list index out of range
Edit and run this code in your browser

Live Python

What Python says when these go wrong

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Indentation decides what repeats
for n in [1, 2, 3]:
    print("inside the loop:", n)
print("after the loop: done")
inside the loop: 1
inside the loop: 2
inside the loop: 3
after the loop: done
Edit and run this code in your browser

Live Python

Indentation decides what repeats

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

Compare that output with the code: the line that is indented runs three times, and the line that is not runs once, after the loop. Indentation is the only difference.

7 · In Python

A small program with a decision inside a loop

Here is everything from parts 1 and 2 together. Read it before you run it, and predict what it will print.

Decide and repeat in one program
prices = [62.5, 48.0, 71.2, 55.5, 90.0]
budget = 65

within = []
too_high = 0
for price in prices:
    if price <= budget:
        within.append(price)
    else:
        too_high = too_high + 1

print("within budget:", within)
print("too expensive:", too_high)
print("cheapest:", min(within), "| dearest:", max(within))
print("average of the affordable ones:", round(sum(within) / len(within), 2))
within budget: [62.5, 48.0, 55.5]
too expensive: 2
cheapest: 48.0 | dearest: 62.5
average of the affordable ones: 55.33
Edit and run this code in your browser

Live Python

Decide and repeat in one program

Runs in your browser on your device. Nothing you type is sent anywhere, and nothing here changes your saved progress.

Press Ctrl+Enter (⌘+Enter on Mac) to run. Tab moves focus to the next control, as usual; use spaces to indent.

  1. Change budget to 50. How many are too expensive now?
  2. Add a new price to the list, such as 45.5, and check the totals update.
  3. Change <= to < in the condition. Does any answer change? Why?

Stuck on a symbol? Keep the Python cheat sheet open in another tab.