Skip to ContentGo to accessibility pageKeyboard shortcuts menu
OpenStax Logo

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.

Checkpoint

For loop example for iterating over a container object

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)
1.
What is the program's output?
  1. 7
  2. 8
  3. 9
2.
What's the code's output if the line count += 1 is replaced with count *= 2?
  1. 0
  2. 16
  3. 28
3.
What is printed if the code is changed as follows?
str_var = "A string"

count = 0
for c in str_var:
  count += 1
  # New line
  print(c, end = '*')

print(count)
  1. A string*
  2. A*s*t*r*i*n*g*
  3. A* *s*t*r*i*n*g*

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

range(end)

  • Generates a sequence beginning at 0 until end.
  • Step size: 1

range(4)

0, 1, 2, 3

range(start, end)

  • Generates a sequence beginning at start until end.
  • Step size: 1

range(0, 3)

0, 1, 2

range(2, 6)

2, 3, 4, 5

range(-13, -9)

-13, -12, -11, -10

range(start, end, step)

  • Generates a sequence beginning at start until end.
  • Step size: step

range(0, 4, 1)

0, 1, 2, 3

range(1, 7, 2)

1, 3, 5

range(3, -2, -1)

3, 2, 1, 0, -1

range(10, 0, -4)

10, 6, 2

Table 5.1 Using the range() function.

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
Table 5.2

Concepts in Practice

For loop using a range() function

4.
What are the arguments to the range() function for the increasing sequence of every 3rd integer from 10 to 22 (inclusive of both ends)?
  1. range(10, 23, 3)
  2. range(10, 22, 3)
  3. range(22, 10, -3)
5.
What are the arguments to the range() function for the decreasing sequence of every integer from 5 to 1 (inclusive of both ends)?
  1. range(5, 1, 1)
  2. range(5, 1, -1)
  3. range(5, 0, -1)
6.
What is the sequence generated from range(-1, -2, -1)?
  1. 1
  2. -1, -2
  3. -2
7.
What is the output of the range(1, 2, -1)?
  1. 1
  2. 1, 2
  3. empty sequence
8.
What is the output of range(5, 2)?
  1. 0, 2, 4
  2. 2, 3, 4
  3. empty sequence

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:

  1. Prints all even numbers between the two provided numbers (inclusive of both), in ascending order.
  2. 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.

Citation/Attribution

This book may not be used in the training of large language models or otherwise be ingested into large language models or generative AI offerings without OpenStax's permission.

Want to cite, share, or modify this book? This book uses the Creative Commons Attribution License and you must attribute OpenStax.

Attribution information
  • If you are redistributing all or part of this book in a print format, then you must include on every physical page the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
  • If you are redistributing all or part of this book in a digital format, then you must include on every digital page view the following attribution:
    Access for free at https://openstax.org/books/introduction-python-programming/pages/1-introduction
Citation information

© Jul 30, 2024 OpenStax. Textbook content produced by OpenStax is licensed under a Creative Commons Attribution License . The OpenStax name, OpenStax logo, OpenStax book covers, OpenStax CNX name, and OpenStax CNX logo are not subject to the Creative Commons license and may not be reproduced without the prior and express written consent of Rice University.

This book utilizes the OpenStax Python Code Runner. The code runner is developed by Wiley and is All Rights Reserved.