Adding 1 to 5 with a for loop
To add 1, 2, 3, 4 and 5 we repeat the same step five times: add the next number. Whenever a step repeats, we use a loop. First we start the total at 0, so that the sum begins from nothing. Then for i in range(1, 6) visits the numbers 1, 2, 3, 4 and 5. Note that range(1, 6) stops before 6, so 6 is not visited. Inside the loop, total += i adds the current number to the total. When the loop ends, the program shows 15. A trace table helps to see the loop: write the value of i and the total after each turn. Python is case sensitive, so the name must be written the same each time: i and I would be two different names.
| A | B | |
|---|---|---|
| 1 | i | total after adding |
| 2 | 1 | 1 |
| 3 | 2 | 3 |
| 4 | 3 | 6 |
| 5 | 4 | 10 |
| 6 | 5 | 15 |
1total = 0 2for i in range(1, 4): 3 total += i 4print(total)
6
Mona has three marks: 45, 60 and 52. The rule, decided by a person, is: pass if the average is at least 50. Write the four skills, then the idea of the code (three inputs, the average with brackets, if and else). What does the program show for her marks?