Iterate Over Sequences Using For and While Loops¶
Date published: 2018-02-18
Category: Python
Subcategory: Beginner Concepts
Tags: lists, loops
Let's start with a simple list of grocery bills to illustrate these concepts.
groceries = ["carrots", "soup", "spinach"]
We want to use loops in Python to repeat similar tasks.
for statements to loop¶
For loops allow you to iterate over a sequences (such as a list or string) in the order they appear in the sequence.
for grocery in groceries:
print(grocery)
carrots soup spinach
We're essentially saying for each element in the groceries
list, print each element to a new line.
A for loop has a header that ends with a colon and an indented body below.
A for statement is called a loop because the flow of execution is through the body, and then back up to the header.
The loop terminates when we've iterated over all elements of the Python sequence.
range() function¶
The range()
function helps iterate over a sequence of numbers.
We can print the numbers from 0 to 3.
for number in range(4):
print(number)
0 1 2 3
range(4)
generates 4 values; however, we start counting at 0 so we only print up to 3.
We can also specify any start and end value as arguments to the range()
function.
for number in range(4, 6):
print(number)
4 5
A third optional argument could be a step - an increment with each iteration from start to end.
for even_number in range(4, 9, 2):
print(even_number)
4 6 8
Our step value of 2 helps us print just even numbers since we start at 4 - an even number.
While loop¶
A while loop implements repeated code based on a given Boolean condition.
The code in the while loop will execute as long as the while statement evaluates to True.
For the last line in the code block below, number
gets a reassignment update to get the old value, which starts at 5, and with each loop, update number
to a new value with an addition of 1. Updating a variable by a positive amount is called an increment. Updating by a negative amount is considered a decrement.
number = 5
while number < 8:
print(number)
number += 1 # increments the number value by 1
5 6 7
The code executed in the body of the while loop three times since 5, 6 and 7 are each smaller than 8.
Once our number was equal to 8, then the while condition evaluated to False, since 8 is not less than 8, and the execution of the while loop ended.