Python, lesson 5
Computers are good at doing the same thing many times without getting bored. A loop runs
a block of code again and again. Python has two kinds: for and while.
A for loop walks through the items of a sequence, one at a time:
To count, loop over range(). It produces numbers on demand, and the stop value is
not included:
If the start is already past the stop, the range is empty and the loop body never runs. That's usually what you want: looping zero times is not an error.
A common pattern is an accumulator: a variable that starts empty and grows on each pass.
A while loop keeps going as long as its condition is true. Use it when you don't know in
advance how many passes you need:
Make sure something inside the loop eventually makes the condition false, or the loop never ends. If a program seems to hang, an endless is the first suspect.
2 exercises to try what you just read.
whilebreak leaves the loop immediately.continue skips the rest of this pass and moves on to the next one.A very common shape is while True: with a break once you see a stop signal:
A loop can have an else block. It runs only if the loop finished without hitting
break. It's handy for searches:
Reach for for when you are walking through something or counting to a known number. Reach
for while when you are waiting for something to happen.
Read a whole number n (0 or more). Print the numbers from n down to 1, one per line, then
print Liftoff!. If n is 0, print only Liftoff!.
Sample input:
Sample output:
A shop till reads prices, one per line, until it sees the line done. Print how many items
were scanned and the total, formatted with two decimals, like this:
Sample input:
for fruit in ["apple", "pear", "plum"]:
print(f"I like {fruit}")
for letter in "abc":
print(letter) # a string is a sequence of charactersfor i in range(5): # 0 1 2 3 4
print(i)
for i in range(1, 6): # 1 2 3 4 5
print(i)
for i in range(10, 0, -2): # 10 8 6 4 2 (the third number is the step)
print(i)total = 0
for n in range(1, 101):
total += n
print(total) # 5050balance = 100
years = 0
while balance < 200:
balance *= 1.07
years += 1
print(years)while True:
line = input()
if line == "quit":
break
if line == "":
continue # ignore blank lines
print(f"You said {line}")for n in [3, 7, 11]:
if n % 2 == 0:
print("found an even number")
break
else:
print("no even numbers")33
2
1
Liftoff!items: 3
total: 7.252.50
1.25
3.50
done