Chapter 2 · Decide, repeat, reuse
Decisions and loops
Step 1 of 22 · Concept
Questions with True or False answers
By the end of this lesson your programs decide and repeat.
Both start with a question whose answer is True or False (lesson 3): Python calls it a condition.
| condition | means | with a = 7, b = 10 |
|---|---|---|
a < b | less than | True |
a > b | more than | False |
a <= b | at most | True |
a >= b | at least | False |
a == b | equal | False |
a != b | not equal | True |
Step 2 of 22 · Concept
if runs an indented block
temp = 30
if temp > 25:
print("Hot")
else:
print("Not hot")
print("Done")
ifchecks a condition. When it isTrue, the block under it runs.- A
:ends the condition. The block is the lines under it, indented: any equal number of spaces works, and 4 is what everyone uses. else:has its own block, forFalse. A block ends where its indentation does.
Step 3 of 22 · Try it
Try it: fix the block
Run it. Python stops before any line runs, at the first mistake it finds.
Fix that one and run again, as in lesson 5. After two fixes the program prints Not hot.
Python says SyntaxError: expected ':', then IndentationError: expected an indented block after 'else' statement on line 4. Line 4 needs a : at its end; line 5 needs the 4 spaces that line 3 has.
Step 4 of 22 · Concept
More than two choices: elif
For more than two choices, chain the conditions with elif (else if).
- Python checks the conditions from the top, one by one.
- It runs the block of the first condition that is
True, and skips the rest. elseat the end catches everything left.
Step 5 of 22 · Quiz
What will it print?
Type exactly what this program prints.
score = 72
if score >= 90:
print("Grade: A")
elif score >= 70:
print("Grade: B")
else:
prnt("Grade: C")
Step 6 of 22 · Demo
See it run
Run it and compare with your answer. Then change score to 95, then 40, and run it each time.
With 40 the else block runs at last, and Python stops at prnt. Fix the name.
Step 7 of 22 · Quiz
Two conditions at once: and, or, not
| write | True when |
|---|---|
a and b | both are True |
a or b | at least one is True |
not a | a is False |
Type exactly what this program prints.
x = 7
print(x >= 7 and x < 10)
print(x < 0 or x > 10)
print(not (x > 10))
answer = "no"
if answer == "y" or "yes":
print("You said yes")
Step 8 of 22 · Demo
See the trap
Run it and compare with your answer. Then compare each side in the if, answer == "y" or answer == "yes", and
run it again: the last line is gone.
Step 9 of 22 · Exercise
Your turn: not a score
A score must be from 0 to 100. Add a first check: when score is below 0 or above 100, print Not a score.
With score = 120 the program must print:
Not a score
The new check goes first: the first True condition wins, and 120 would get an A otherwise.
Ask whether score is below 0 or above 100, with its own print. The old first if becomes an elif.
if score < 0 or score > 100:
Step 10 of 22 · Concept
A for loop counts for you
for i in range(1, 6):
print(i)
- A
forloop runs its block once for each number: one round each. range(1, 6)gives 1, 2, 3, 4, 5: it stops before 6.range(5)gives 0 to 4: five rounds, from 0.- In each round,
ipoints at the next number. The block is indented, asif's is.
Step 11 of 22 · Quiz
Predict the rounds
Type exactly what this program prints.
for i in range(5):
if i % 2 == 0:
print(i, "is even")
else:
print(i, "is odd")
Step 12 of 22 · Demo
A loop and a decision
An if inside a for: every round decides again. Its blocks are indented twice. Run it and compare with your
answer.
Step 13 of 22 · Trace
Watch the names change
total and i are names in the <module> frame (lesson 2). Their numbers are drawn in their boxes, the shorthand
of lesson 3. Press Next to run one round at a time.
total = 0
for i in range(1, 4):
total += i
print("Sum:", total)- The loop starts:
iis 1,totalis 0. Line 3 is next. total += imadetotal1. The next round madei2.totalis 3,iis 3. Line 3 is next again.totalis 6.range(1, 4)has no number left, so the loop is over.ikeeps its last value, 3.- Line 4 printed
Sum: 6. The program is finished.
Step 14 of 22 · Exercise
Your turn: 1 to 100
Add up all the numbers from 1 to 100 with a for loop. The program must print:
Sum: 5050
Watch total grow, as in the trace: after 1 it is 1, after 2 it is 3, after 3 it is 6.
A for over range(1, 101): the stop is not included, so 100 is. Inside it, add i to total.
for i in range(1, 101):
Step 15 of 22 · Concept
while: repeat until
n = 1
while n < 100:
print(n)
n = n * 2
print("Past 100:", n)
while repeats its block as long as its condition is True. Use it when you do not know in advance how many
rounds you need.
Step 16 of 22 · Try it
Try it: a loop that never ends
Run it. It does not stop by itself: n stays 1, so n < 100 stays True.
Press Stop. Then put n = n * 2 in place of the comment, indented as print(n) is, and run it again.
Step 17 of 22 · Exercise
Your turn: the road to 1
A famous puzzle. Start from a number n, and repeat:
- if
nis even, halve it; - if
nis odd, make it3 * n + 1.
The number always seems to reach 1. Nobody has proved that it always does.
Start from n = 6. Apply the rule with a while loop until n is 1, and print each new value. The program must
print:
6
3
10
5
16
8
4
2
1
Halve with //, not /. / always gives a float, so 6 / 2 is 3.0 and the output shows 3.0.
A while that runs as long as n is not 1. Inside it, an if on whether n is even with an else, then print(n) after both blocks.
while n != 1:
Step 18 of 22 · Quiz
Order matters
A program has run n = 15. Which block of this chain runs?
if n % 3 == 0:
print("Fizz")
elif n % 15 == 0:
print("FizzBuzz")
Step 19 of 22 · Exercise
Your turn: FizzBuzz
Print the numbers from 1 to 15, each on its own line, but:
FizzBuzzinstead of a number divisible by 3 and by 5,Fizzinstead of a number divisible by 3,Buzzinstead of a number divisible by 5.
The output starts 1, 2, Fizz, 4, Buzz and ends with FizzBuzz.
n % 3 == 0 is True when n divides by 3. Divisible by 3 and by 5 means n % 15 == 0: check that first.
Inside the loop, one chain of four: divisible by 15, else by 3, else by 5, else the number itself.
if n % 15 == 0:
Step 20 of 22 · Check yourself
Check yourself: multiples of 7
Print the first seven multiples of 7, one per line, then a count:
- Loop
ifrom 1 to 7;n = 7 * iis the next multiple. - Print
n, with*after it whennis even or over 40. - After the loop, print
Marked:and how many got a*.
The output must be exactly:
7
14 *
21
28 *
35
42 *
49 *
Marked: 4
Set the count to 0 before the loop. In the loop, one if and its else, as in the even and odd demo: the if block prints the * and adds 1.
Step 21 of 22 · Challenge · optional
Challenge: countdown
Optional.
Count down from 10 to 1 on one line, then Liftoff!. The output must be exactly:
10 9 8 7 6 5 4 3 2 1 Liftoff!
range takes a third number, the step: what it adds each round. A step of -1 counts down.
range(10, 0, -1) gives 10, 9, ..., 1: it stops before 0. Build the line in a name, as total grew: line += str(i) + " " (lesson 4).
line = ""
for i in range(10, 0, -1):
Step 22 of 22 · Recap
Recap
- A condition such as
score >= 70givesTrueorFalse. if/elif/elsewith a:and an indented block: the firstTruecondition wins.andneeds both sidesTrue,orat least one; compare each side.range(1, 6)gives 1 to 5: the stop is not included.whilerepeats while its condition isTrue. Something inside must change it, or press Stop.
Next: lesson 7 names a piece of work and calls it: functions.
Review
4 questions from this lesson, in a new order each time. Answer from memory: 3 of 4 right on the first try passes. On a day after you finish the lesson, a pass earns 15 XP.
The review needs JavaScript.
temp = 20
if temp > 25:
print("Hot")
else
print("Not hot")
score = 72
if score >= 90:
print("Grade: A")
elif score >= 70:
print("Grade: B")
else:
prnt("Grade: C")
x = 7
print(x >= 7 and x < 10)
print(x < 0 or x > 10)
print(not (x > 10))
answer = "no"
if answer == "y" or "yes":
print("You said yes")
score = 120
if score >= 90:
print("Grade: A")
elif score >= 70:
print("Grade: B")
else:
print("Grade: C")
for i in range(5):
if i % 2 == 0:
print(i, "is even")
else:
print(i, "is odd")
total = 0
# add every number from 1 to 100 to total
print("Sum:", total)
n = 1
while n < 100:
print(n)
# something is missing here
print("Past 100:", n)
n = 6
print(n)
# while n is not 1:
# halve n if it is even, else make it 3 * n + 1
# then print n
for n in range(1, 16):
print(n)
# 1. loop i from 1 to 7: n = 7 * i
# 2. print n, with a * when n is even or over 40
# 3. print Marked: and how many got a *
print("Liftoff!")