Skip to main content

For Loop

Note☆ Learning Objectives
  • Explain the purpose of the for, break and continue statements
  • Write for loops statements using correct syntax
  • Identify when a for loop is better than typing the same lines of code many times
  • Construct a for loop using different forms of the range function

A for loop allows you to repeat lines of code n amount of times. Imagine a guessing game coded in python which lets the player guess a number. What if the game would like to let the player have 10 tries. A for loop repeats the statement while counting the “turns” .

The for loop is actually capable of handling more complex tasks, such as iterating through large collections of data, item by item. We’ll explore that in more detail soon, but for now, we’ll focus on a simpler use of the for loop.

Example:

for item in sequence:
    # loop body

Here are some key elements to understand:

Generic for loop

A for loop can be generalized to something that looks like:

Note: Using sequence in the following instructions is not exactly correct, but it is reasonable to think of sequences for now.

forvariableinsequence

Where

  • variable is just the name of a variable. It can be any valid variable name

  • sequence is something that can be looped over

    Sounds like a circular argument, I know, but its the best we can do at this level.

Examples of sequence

Think of sequences a a list of things to be processed. Like a stack of papers to grade, or a to-do list, or a series of numbers to process.

range():

When within a for loop,

  • range(n) will provide the sequence of numbers

    \[0, 1, 2 ,... n-1\]

  • range(start, end) will provide the sequence of numbers

    \[\text{start}, \text{start}+1, \text{start} + 2 ,... \text{end}-1\]

  • range(start, end, step) will provide the sequence of numbers

    \[\text{start}, \text{start}+\text{step}, \text{start} + 2*\text{step} ,... \text{end}-1\]

string

When within a for loop,

  • string_variable will provide the individual characters of the string, one character at a time
for letter in my_name:
    print(letter)

Lists and Files are topics taught later in the course, so you may want to skip these for now and come back later.

list

When within a for loop,

  • list_variable will provide the contents of the list, one element at a time

file

When within a for loop,

  • file will provide the contents of the file, one line at a time

How does a for loop work?

Given the following code

for variable in sequence:
  print(variable)

As the code starts, the variable will be set to the very 1st thing in the sequence (whatever that thing is)

When the code has finished executing everything in the code block (indicated by indentations), then

  • the code goes back to the beginning of the for loop, and
  • variable will be set the the next thing in the sequence

This will continue until there are no things left in the sequence.

The range() function

In Python, the range()function returns a sequence of numbers.

Example:

values = range(4)

Here, range(4) returns a sequence of 0, 1, 2 ,and 3.

Since the range() function returns a sequence of numbers, we can iterate over it using a for loop.

1    for i in range(3):
2        print(f"I am at index {i}")
3    print("all done")

Code trace:

code line # i output printed to console comment
1 0 i is set to 1st number in the range sequence (0, 1, 2)
2 I am at index 0
1 1 i is set to 2nd number in the range sequence (0, 1, 2)
2 I am at index 1
1 2 i is set to 3rd number in the range sequence (0, 1, 2)
2 I am at index 2
1 There are no more numbers in the range sequence, so for loop quits
3 all done No longer in the for loop

Example:

output:

The value of i is currently 0
The value of i is currently 1
The value of i is currently 2
The value of i is currently 3
The value of i is currently 4

The loop has been executed 5 times (it’s the range() function’s argument), the last control variable’s value is 4 (not 5, as it starts from 0, not from 1)

Two arguments range() function

The range() function invocation may be equipped with two arguments, not just one:
range(start, end)

⚠️ Note: the range() function accepts only integers as its arguments, and generates sequences of integers.

Example:

In this case, the first argument determines the initial (first) value of the control variable. The last argument shows the first value the control variable will not be assigned.

output:

The value of i is currently 2
The value of i is currently 3
The value of i is currently 4
The value of i is currently 5
The value of i is currently 6
The value of i is currently 7

The first value shown is 2 (taken from the range()’s first argument.), and the last is 7 (although the range()’s second argument is 8).

Three arguments range() function

The range() function may also accept three arguments:
range(start, end, step)

Example:

The third argument is an increment or step. Its value will be added to the control variable at every loop turn (as you may suspect, the default value of the increment is 1).

output:

The value of i is currently 2
The value of i is currently 5

The break statement

Sometimes, you may want to stop your for loop from repeating after a certain condition is met. For example, your for loop might be looking for a number that satisfies some condition. Once found, you want to stop the loop from going any further.

To do this, use the break statement to escape or break out of the loop.

Any statements inside the body of the for loop beyond the break statement will be skipped over and the control flow will pick up again after the end of the loop.

Example break

The continue statement

The continue statement is similar to the break statement in that it skips the rest of the for loop body, but unlike break it does not stop the loop. Instead, it jumps back to the top of the loop for the next number.

Example continue

Looping through the characters of a string

Code trace:

code line # Character output printed to console comment
1 s character is set to 1st character in name “Sandy”
2 Character: S
1 a character is set to 2nd character in name “sandy”
2 Character: a
1 n character is set to 3rd character in name sandy”
2 Character: n
1 d character is set to 4th character in name sandy”
2 Character: d
1 y character is set to 5th character in name sandy”
2 Character: y
1 There are no more characters in name, so quit for loop
3 all done No longer in the for loop

Looping through the items in a list

WarningNote

If you haven’t learned Lists yet, then you should skip this section and come back later.

Code trace:

code line # number output printed to console comment
1 1 number is set to 1st number in the fib_list [1, 1, 2, 3, 5 ]
2 The next fibonacci number is 1
1 1 number is set to 2nd number in the fib_list [1, 1, 2, 3, 5 ]
2 The next fibonacci number is 1
1 2 number is set to 3rd number in the fib_list [1, 1, 2, 3, 5 ]
2 The next fibonacci number is 2
1 3 number is set to 4th number in the fib_list. [1, 1, 2, 3, 5 ]
2 The next fibonacci number is 3
1 5 number is set to 5th number in the fib_list. [1, 1, 2, 3, 5 ]
2 The next fibonacci number is 5
1 There are no numbers left in the fib_list, so quit for loop
3 all done No longer in the for loop

Examples of Loops Inside Functions

WarningNote

If you haven’t learned custom functions yet, then you may want to skip this section and come back later.

A for loop is often used inside functions to automate repetitive tasks. Here’s a breakdown of how loops work with functions in Python.

Example 1: Simple Function with a For Loop

This function prints the numbers from 1 to 5 using a for loop:

Explanation: The for i in range(1, 6) loop iterates over the numbers from 1 to 5, printing each value.

Example 2: Sum of All Integers from 1 to limit

This function calculates the sum of all integers from 1 to a given number limit.

See how we did limit+1 as the end of the sequence because we wanted limit to be included.

Explanation: The function uses a loop to sum up all the integers from 1 to limit. When called with limit = 5, it returns 15.

Example 3: Sum of Squares

Explanation: The function loops through numbers from 1 to limit and adds the square of each number to the total. For limit = 4, the result is 30.