A brief note on Loops: the for loop and range(), loops that build totals, counts and products, a loop inside a loop, the while loop, break and continue, and choosing the right loop. With a worked example, practice, a program and questions to check yourself.
A brief note on Loops. Read it before a test. Try each question at the end before you open its answer.
for loop repeats its indented lines once for every value it is given: for name in ["Ali", "Bina", "Chen"]:.for letter in "cat": has one round for each letter.| Call | The numbers it gives |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(2, 6) | 2, 3, 4, 5 |
range(1, 10, 3) | 1, 4, 7 |
range(5, 0, -1) | 5, 4, 3, 2, 1 |
n, the stop must be n + 1.range(a, b) gives b - a numbers. A negative step counts down.print(..., end="") keeps the output on the same line. A plain print() after the inner loop starts a new line.row and col.while condition: repeats its body as long as the condition is True. The condition is asked before every round, even the first.while loop needs three things: a start, a test and a change. If nothing changes, the loop never ends.break leaves the loop at once. continue skips the rest of this round and goes to the next.while True: runs until a break, so the break must be able to happen.| Use | When |
|---|---|
for | you know the number of rounds, or you go through the items of something |
while | you repeat until something happens |
A water tank holds 50 litres. Every hour, half of the water is used, in whole litres. How many hours pass before it holds 10 litres or less?
Follow it with a trace table. The test comes before every round.
| Round | litres > 10? | litres | hours |
|---|---|---|---|
| start | 50 | 0 | |
| 1 | yes | 25 | 1 |
| 2 | yes | 12 | 2 |
| 3 | yes | 6 | 3 |
| test | no, stop | 6 | 3 |
litres is 50 and hours is 0, before the loop.litres with //, so the test can become false.6 > 10 is false. The program shows 6 litres after 3 hours.Mira reads 25 pages of a 180-page book every day. The program counts the days and draws a bar of # for every 10 pages read.
IndentationError: expected an indented block after 'for' statement on line 1.range(1, 10) stops at 9. To include 10, write range(1, 11).total = 0 inside the loop sets the total back to 0 in every round. Put it before the loop.range() gives exactly these numbers?product = 0 before the loop and product = product * k inside it. What does he get, and how does he fix it?for or while: (a) show the names of the 12 months; (b) keep asking for a password until it is right.Log in to join the discussion.
Loading…