Control FlowLesson 7 of 1914 min
for Loops and range()
Repeat work once per item — over a range of numbers, the characters of a string, or any collection.
By the end you will be able to
- Loop over a sequence with for
- Generate number sequences with range()
- Accumulate a running total inside a loop
A for loop runs its body once per item in a collection, assigning each item to the loop variable in turn.
I am learning Python
I am learning Rust
I am learning Go
c
a
t
— expected output; press Run to execute it yourselfrange()
range() generates a sequence of integers on demand. It comes in three forms, and — like slicing — the stop value is excluded.
range(5)→ 0, 1, 2, 3, 4range(2, 6)→ 2, 3, 4, 5range(0, 10, 3)→ 0, 3, 6, 9
0 1 2 3 4
2 3 4 5
10 8 6 4 2
— expected output; press Run to execute it yourselfAccumulating a result
The most common loop pattern: start with an empty or zero accumulator outside the loop, update it inside, then use it after.
Total: 28.50
Average: 7.12
— expected output; press Run to execute it yourselfenumerate(): index and value together
When you need the position as well as the item, enumerate() gives you both, and is far less error-prone than managing a counter by hand.
1. write
2. test
3. ship
— expected output; press Run to execute it yourselfExercise
Write a function sum_even(n) that returns the sum of all even numbers from 1 up to and including n. sum_even(10) should return 30 (2+4+6+8+10).
Press Run to execute this code.