for and while Loops
The for range and while loops: iteration, accumulators and standard tricks.
Python's for loop iterates over the elements of a sequence. To iterate over numbers use range:
• range(5) — the numbers 0, 1, 2, 3, 4 (five numbers, starting at zero!);
• range(1, 6) — the numbers 1, 2, 3, 4, 5 (the right bound is excluded);
• range(10, 0, -2) — 10, 8, 6, 4, 2 (the third argument is the step).
The excluded right bound of range is the source of endless off-by-one errors. Check your bounds on a small example.
Python
A counter from 1 to 5
The main loop technique is accumulation: create a variable and update it on every step. Below — reading n numbers and computing their sum.
Python
Enter: 4, then the line 10 20 30 40
The while loop repeats as long as its condition is true — you need it when the number of steps is unknown in advance.
Python
How many times is the number divisible by 2? Enter: 96
Task: print all even numbers from 2 to 20 on one line (hint: print has an end parameter, print(x, end=" ") does not move to a new line).
Then solve the attached problems "Factorial" and "Sum of Array Elements" — and mark the lesson as completed.