Python for loops and range()

The for loop is Python's count-controlled iteration construct, tested in every UK GCSE Computer Science specification. This unit covers the two main patterns learners meet at KS3, KS4 and GCSE: for i in range(n) for numeric loops (including the three-argument form range(start, stop, step)), and for item in sequence for iterating over strings and lists. It also introduces nested for loops for grids and tables. Every example runs in the browser so learners can experiment with the loop bounds and see the effect immediately. Perfect for classroom teaching, GCSE and A Level revision, and independent or home-schooled learners.


What you'll learn

  • Use for i in range(n) to loop a known number of times
  • Read range(start, stop) and range(start, stop, step)
  • Iterate over strings and lists directly with for x in sequence
  • Use nested loops for grids and multi-dimensional data
  • Choose for over while when the number of iterations is known

UK GCSE topic coverage

  • Count-controlled iteration
  • range() with start
  • range() with step
  • Running totals in a for loop
  • for + if
  • for over characters
  • for + range for pure repetition
  • for + range for shapes
  • Modules (`random`) and iteration
  • Applied for loops

Worked example

Print the 7-times table using range()

for i in range(1, 13):
    print(f"7 x {i} = {7 * i}")

Try a full unit free with a RunPy account

Sign up free and get the whole of Unit 1 (Input, Output and Variables) with checked tasks and instant feedback, plus a selection of the exam-style questions so you can practice on real GCSE-style content before upgrading.


Lessons in this unit

Full interactive lessons with checked tasks are available to signed-in RunPy users. Unit 1 and a selection of exam-style questions are free with a RunPy account.

  1. Introducing for loops and range(stop)
  2. Using range(start, stop)
  3. Using range(start, stop, step)
  4. Accumulators with for loops
  5. Combining for loops with selection
  6. Iterating over strings with for
  7. Using range() to control repetition
  8. Generating patterns with range()
  9. Using random in loops
  10. Composite algorithm challenge

Frequently asked questions

Does range(10) include 10?
No. range(10) produces 0 through 9. The stop value is exclusive. To include 10 you'd write range(1, 11).
Can I loop over a string?
Yes. for c in "hello": will give you each character in turn. Very useful for character-by-character processing at GCSE.
What is range(0, 10, 2)?
The three-argument form: start at 0, stop before 10, step by 2. Produces 0, 2, 4, 6, 8. Use negative step values to count down.