Learning objectives
By the end of this section you should be able to
- Explain the
for
loop construct. - Use a
for
loop to implement repeating tasks.
For loop
In Python, a container can be a range of numbers, a string of characters, or a list of values. To access objects within a container, an iterative loop can be designed to retrieve objects one at a time. A for loop iterates over all elements in a container. Ex: Iterating over a class roster and printing students' names.
Concepts in Practice
For loop over a string container
A string variable can be considered a container of multiple characters, and hence can be iterated on. Given the following code, answer the questions.
str_var = "A string"
count = 0
for c in str_var:
count += 1
print(count)
Range()
function in for loop
A for
loop can be used for iteration and counting. The range()
function is a common approach for implementing counting in a for
loop. A range() function generates a sequence of integers between the two numbers given a step size. This integer sequence is inclusive of the start and exclusive of the end of the sequence. The range()
function can take up to three input values. Examples are provided in the table below.
Range function | Description | Example | Output |
---|---|---|---|
|
|
|
|
|
|
|
|
|
|
||
|
|
||
|
|
|
|
|
|
||
|
|
||
|
|
Example 5.2
Two programs printing all integer multiples of 5 less than 50 (Notice the compactness of the for
construction compared to the while
)
# For loop condition using
# range() function to print
# all multiples of 5 less than 50
for i in range(0, 50, 5):
print(i)
|
# While loop implementation of printing
# multiples of 5 less than 50
# Initialization
i = 0
# Limiting the range to be less than 50
while i < 50:
print(i)
i+=5
|
Concepts in Practice
For loop using a range() function
Try It
Counting spaces
Write a program using a for
loop that takes in a string as input and counts the number of spaces in the provided string. The program must print the number of spaces counted. Ex: If the input is "Hi everyone"
, the program outputs 1
.
Try It
Sequences
Write a program that reads two integer values, n1
and n2
, with n1 < n2
, and performs the following tasks:
- Prints all even numbers between the two provided numbers (inclusive of both), in ascending order.
- Prints all odd numbers between the two provided numbers (exclusive of both), in descending order.
Input: 2 8
Prints: 2 4 6 8 7 5 3
Note: the program should return an error message if the second number is smaller than the first.