For Loop
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 bodyHere are some key elements to understand:
- The for keyword starts the loop, and no condition is needed as the loop manages this internally.
- The variable following the for keyword, known under the names control variable, loop variable or iteration variable automatically tracks the loop’s iterations.
- The in keyword defines the sequence of values the control variable will iterate over.
- The loop body can contain almost any Python code you know. i.e. you can have variables, print(), if-else statements…even more
forloops!
- In the example
for item in sequence:, the loop will go through each item in the sequence and perform the specified action.
Generic for loop
A for loop can be generalized to something that looks like:
Note: Using
sequencein the following instructions is not exactly correct, but it is reasonable to think of sequences for now.
forvariableinsequence
Where
variableis just the name of a variable. It can be any valid variable namesequenceis something that can be looped overSounds 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_variablewill provide the individual characters of the string, one character at a time
for letter in my_name:
print(letter)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 4The 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 7The 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 5The 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
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
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.