Python from zero · Part 2 of 6 · No experience needed
Python from zero, part 2: decisions and repeats
1 · Observe
Real work is deciding and repeating
| Word | What it means |
|---|---|
| Condition | A question whose answer is True or False, such as price <= 70. |
| if / elif / else | If the condition is true do this, else if another is true do that, otherwise do the last thing. |
| Indentation | The spaces at the start of a line. In Python they are part of the meaning. |
| List | An ordered collection of values in square brackets: [62.5, 48.0, 71.2]. |
| Index | A value's position in a list. Counting starts at 0. |
| Loop | Repeating the same steps for each value. |
| Accumulator | A 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.
| You say | Python writes | Meaning |
|---|---|---|
| If the price is within budget | if price <= budget: | Do the next, indented, lines only when True |
| Otherwise | else: | Do these lines when the condition was False |
| For each flat in my list | for price in prices: | Run the indented lines once per value |
| Keep a running total | total = total + price | Store 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.
| Word | Means | Example | Answer when price = 62.5 |
|---|---|---|---|
| and | both must be True | price > 50 and price < 70 | True |
| or | at least one is True | price < 50 or price > 100 | False |
| not | flips the answer | not price > 100 | True |
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.
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].
| Pass | price | price <= 60? | shortlist afterwards |
|---|---|---|---|
| Start | [] | ||
| 1 | 62.5 | False, so skip | [] |
| 2 | 48.0 | True, so keep | [48.0] |
| 3 | 71.2 | False, 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.
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 itEdit 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.
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]
TrueEdit 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.
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: 2Edit 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.
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.
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.3Edit 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.
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 5Edit 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.
6 · Where it goes wrong
Four classic slips
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 rangeEdit 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.
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: doneEdit 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.
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.33Edit 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.
- Change budget to 50. How many are too expensive now?
- Add a new price to the list, such as 45.5, and check the totals update.
- Change <= to < in the condition. Does any answer change? Why?
Stuck on a symbol? Keep the Python cheat sheet open in another tab.