Free preview

100 lessons

Python Done Right

Free preview

Python Done Right · 100 lessons

Learn Python from scratch - syntax through to OOP

No surprise gaps

Actually remember it

Skip what you know

One subscription. All learning paths included.

Our content is best on a larger screen

for loops

For loop overview

Explanation

A for loop iterates over elements of a sequence (list, tuple, or string), executing a block of code once per element:

for element in sequence:
    # body of the loop, indented
  • Loop variable: element holds the current item from the sequence on each iteration
  • Indented block: All indented code runs once per element. Unindented code after the loop runs only after all iterations complete
  • Termination: The loop ends when all elements have been processed

Practice questions

4 questions

Which of the following statements about Python's for loop is true?

Select the correct answer:

+ 3 more questions

range() function

Explanation

The range() function generates a sequence of numbers. It can be called in three ways:

  • range(stop) - sequence from 0 to stop (exclusive). range(n) gives n elements.
  • range(start, stop) - sequence from start to stop (exclusive).
  • range(start, stop, step) - same as above but with a custom increment between numbers.

We can convert a range to a list using list() to see its elements:

print(list(range(4)))          # Output: [0, 1, 2, 3]
print(list(range(1, 6)))       # Output: [1, 2, 3, 4, 5]
print(list(range(1, 10, 2)))   # Output: [1, 3, 5, 7, 9]
Why do we need list() here?

Details

Practice questions

4 questions

In the Python Editor, use the range() function to define a variable called even_500 which contains all the even numbers from 0 up to (and including) 500.

Run the code to find the sum of even_500 and choose from the options below.

Note: if you want to view the elements in a range object to check before submitting, convert it to a list first e.g.

print(list(range(4)))  # Output: [0, 1, 2, 3]

Select the correct answer:

+ 3 more questions

For loops using range()

Explanation

We can combine a for loop with range() to iterate a known number of times:

for i in range(5):
    print(i)
Output

Details

We can use range(start, stop) and perform any logic in the loop body:

for x in range(2, 5):
    print(x ** 2)
Output

Details

Accumulating a value across iterations

A common pattern is to declare a variable before the loop and update it on each iteration:

sum_of_squares = 0
for x in range(2, 5):
    sum_of_squares = sum_of_squares + x ** 2
print(sum_of_squares)  # Output: 29

We must initialise sum_of_squares = 0 before the loop - otherwise on the first iteration, the right-hand side would reference a variable that doesn't exist yet.

Practice questions

4 questions

Write a for loop which calculates the sum of squares of the numbers from 0 to 50 (inclusive).

What is the total?

Select the correct answer:

+ 3 more questions

Iterating over lists, tuples and strings

Explanation

Lists, tuples, and strings are all iterable - we can loop over them with a for loop. It's good practice to name the loop variable something that relates to the sequence.

Iterating over a list

fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:
    print(fruit)
Output

Details

Iterating over an empty list simply skips the loop body:

empty_list = []
for entry in empty_list:
    print("Hello!")  # never runs

Iterating over tuples

colours = ('red', 'green', 'blue')

for colour in colours:
    print(colour)
Output

Details

Iterating over strings

Each character (including spaces) is visited one at a time:

word = "Hello"

for character in word:
    print(character)
Output

Details

Warning

When iterating over a mutable sequence like a list, we must not alter its size inside the loop (e.g. appending or removing elements). Doing so raises a RuntimeError.

Practice questions

4 questions

You are given two sequences: list_data and tuple_data. Write two for loops to do the following:

  1. In the first for loop, divide each element in list_data by 1.25 and calculate the sum. Store this result in a variable (e.g., list_total).
  2. In the second for loop, divide each element in tuple_data by 2.5 and calculate the sum. Store this result in a different variable (e.g., tuple_total).

What are the values of list_total, tuple_total and list_total + tuple_total?

Select the correct answer:

+ 3 more questions