Course 4.1Lesson 3 of 5
A loop can build an answer. Make a variable before the loop with the right starting value, change it in every round, and show it after the loop. A total starts at 0 and adds, a product starts at 1 and multiplies, and a counter starts at 0 and adds 1 when a condition is True. If the starting line is inside the loop, the variable starts again in every round, and the answer is wrong. A trace table, with a row for each round, shows what a loop does and finds mistakes. Text can also be built in a loop with stars or letters.
Try the code and the simulations beside the lesson.
After this lesson you can
A loop can add up numbers. The idea has three steps.
total = 0.total = total + i.If you are not sure what a loop does, write a trace table, with one row for each round. Put the loop variable and the answer so far in the columns.
| Round | i | total before | total after |
|---|---|---|---|
| 1 | 1 | 0 | 1 |
| 2 | 2 | 1 | 3 |
| 3 | 3 | 3 | 6 |
| 4 | 4 | 6 | 10 |
The trace is one of the best ways to understand a program, to check it, and to find its mistakes.
What happens if the line total = 0 is inside the loop?
total = 0 comes before the loop, so it runs once. Inside the loop it would set the total back to 0 in every round.
To count how many items pass a test, start a counter at 0, and add 1 when the test is True.
The factorial of 5 is 5 times 4 times 3 times 2 times 1. A loop can multiply in the same way as it added. But the starting value is 1, not 0. A starting 0 would make every product 0.
A loop can also build a picture out of text. In Python, "*" * 3 gives ***. Put it in a loop, and you can draw a triangle.
The same idea works on a text. Look at this program, which counts the vowels.
| You want | Start with | In the loop |
|---|---|---|
| a total | total = 0 | total = total + i |
| a count | count = 0 | count = count + 1, inside an if |
| a product | result = 1 | result = result * i |
if or of count + 1.total + i alone changes nothing. You need total = total + i.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
total = 0 go: before the loop or inside it?result = 1 followed by for i in range(1, 5): result = result * i give?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.