Skip to content
CodeNest

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.

Python
Output
I am learning Python
I am learning Rust
I am learning Go
c
a
t
— expected output; press Run to execute it yourself

range()

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, 4
  • range(2, 6) → 2, 3, 4, 5
  • range(0, 10, 3) → 0, 3, 6, 9
Python
Output
0 1 2 3 4
2 3 4 5
10 8 6 4 2 
— expected output; press Run to execute it yourself

Accumulating a result

The most common loop pattern: start with an empty or zero accumulator outside the loop, update it inside, then use it after.

Python
Output
Total: 28.50
Average: 7.12
— expected output; press Run to execute it yourself

enumerate(): 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.

Python
Output
1. write
2. test
3. ship
— expected output; press Run to execute it yourself

Exercise

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).

Python
Output

Press Run to execute this code.

Check your understanding

0/2 answered
  1. 1.How many times does the body of for i in range(3): run?
  2. 2.What does range(1, 5) produce?