Start free

GCSE · 14 exercises

Python for loops

A for loop repeats its indented lines once for each item: each letter of a string, each item of a list, or each number of a range.

range(5) is 0 to 4; range(1, 6) is 1 to 5; range(10, 0, -1) counts down from 10 to 1.

total = 0
for i in range(1, 6):
    total += i
print(total)  # 15

Watch for: range stops before its end: range(1, n) leaves out n. A print inside the loop prints every time; outside it (not indented), once at the end.

Exercises

  1. Count to nRead n and print the numbers from 1 to n, one per line.Beginner
  2. CountdownRead n and count down from n to 1, one number per line, then print Liftoff!Beginner
  3. Sum from 1 to nRead n and print 1 + 2 + ... + n, using a loop.Beginner
  4. Times tableRead n and print its times table from 1 to 10.Beginner
  5. FactorialThe factorial of n is 1 * 2 * ... * n, and the factorial of 0 is 1.Beginner
  6. Even numbersRead n and print all even numbers from 2 to n on one line, separated by spaces.Beginner
  7. Powers of twoRead n and print the first n powers of two, starting with 1, on one line.Beginner
  8. Table of squaresRead n and print, for every number from 1 to n, the number and its square.Beginner
  9. Add them upRead how many numbers follow, then the numbers, and print their sum.Beginner
  10. Average of n numbersRead n and then n numbers; print their average with two decimals.Beginner
  11. Highest scoreRead n scores and print the highest one, without using max().Beginner
  12. Count the positivesRead n numbers and count how many of them are greater than zero.Beginner
  13. FizzBuzzPrint the numbers from 1 to n, but print Fizz instead of numbers divisible by 3,Beginner
  14. Staircase of starsRead n and print a staircase: row 1 has one star, row 2 has two, up to n stars.Beginner
Start with “Count to n”