Python - For Loops


This lesson covers the following topics:


The Iteration Structure


Also known as a loop, an iteration structure is a programming feature that executes a process repeatedly until a boolean condition is false. Iteration structures use relational operators to test conditions.




All Loops Consist of 3 Parts:

  1. A Control Variable
  2. A Conditional Test
  3. Update to Control Variable
description of gif

For Loops


Although "for" loops can be used in any iteration problem, in practice, they are used when you know how many iterations you're going to make. (A "while" loop should be used when you don't know how many iterations you're going to make.)

In general, for loops are just like while loops. However, for loops combine all three parts of a loop (the control variable, the conditional test, and updating the control variable) in the loop's header.

Python is a little different than most languages because it doesn't simply use an integer as the control variable. Instead, its control variable iterates through a sequence of elements to obtain its value for each iteration. This sequence can consist of numbers, characters, strings, objects, et cetera. That being said, most of the time we still want to iterate through a sequence of numbers, so there is a special function called range() that makes it easy to build that sequence of numbers without having to type them all out individually.

In [1]:
# Here is the syntax of a for loop in Python.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

for i in range(10):
    print(i, end=", ")

print("The loop has terminated.")
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, The loop has terminated.

In the example above, i is the control variable and the range() function returns a sequence of numbers {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}. The control variable, i, is assigned each subsequent value within the sequence for each iteration in the loop.


The Range Function


The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and stops before a specified number.

Function Notes Example Output
range(stop) Returns a sequence of integers in the interval [0, stop). range(5) {0, 1, 2, 3, 4}
range(start, stop) Returns a sequence of integers in the interval [start, stop). range(1, 6) {1, 2, 3, 4, 5}
range(start, stop, step) Returns a sequence of integers in the interval [start, stop),
specifying the incrementation with step.
range(1, 6, 2) {1, 3, 5}


Special Keywords


There are a few special keywords that perform instructions specific to loops.

Keyword Meaning
break With the break statement we can stop the loop even if the while condition is true.
continue With the continue statement we can stop the current iteration, and continue with the next.


Examples


In [2]:
# The example below prints out the squares of the numbers from 1 to 5 (inclusive).
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

for x in range(1, 6):
    print(f"{x} x {x} = {x * x}")
    
print("The loop has terminated.")
1 x 1 = 1
2 x 2 = 4
3 x 3 = 9
4 x 4 = 16
5 x 5 = 25
The loop has terminated.
In [3]:
# Here is an example of a sequence that isn't just a list of numbers.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

for i in ('a', 'b', 'c', 'd', 'e', 'f'):
    print(i, end=", ")
    
print("The loop has terminated.")
a, b, c, d, e, f, The loop has terminated.
In [4]:
# Here is an example of iterating through a string (a string is a sequence of characters).
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

for letter in "Hello World!":
    print(letter)

print("The loop has terminated.")
H
e
l
l
o
 
W
o
r
l
d
!
The loop has terminated.
In [5]:
# Here is an example of a for loop that is counting down.
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

for num in range(10, 0, -1):
    print(num)
    
print("Blast Off!!!")
10
9
8
7
6
5
4
3
2
1
Blast Off!!!
In [6]:
# Here is an example where we add all the even numbers from 1 to 100 (inclusive).
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

sum = 0

for evenNum in range(2, 101, 2):
    sum += evenNum
    
print(f"The sum of even numbers from 1 to 100 (inclusive) is: {sum}")
The sum of even numbers from 1 to 100 (inclusive) is: 2550