Skip to main content
Engineering LibreTexts

5.2: For Loop

  • Page ID
    117550
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \( \newcommand{\dsum}{\displaystyle\sum\limits} \)

    \( \newcommand{\dint}{\displaystyle\int\limits} \)

    \( \newcommand{\dlim}{\displaystyle\lim\limits} \)

    \( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)

    ( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\id}{\mathrm{id}}\)

    \( \newcommand{\Span}{\mathrm{span}}\)

    \( \newcommand{\kernel}{\mathrm{null}\,}\)

    \( \newcommand{\range}{\mathrm{range}\,}\)

    \( \newcommand{\RealPart}{\mathrm{Re}}\)

    \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)

    \( \newcommand{\Argument}{\mathrm{Arg}}\)

    \( \newcommand{\norm}[1]{\| #1 \|}\)

    \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)

    \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \(\newcommand{\longvect}{\overrightarrow}\)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)
    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)
    
    Concepts in Practice \(\PageIndex{1}\): For loop over a string container

    What is the program's output?

    1. 7
    2. 8
    3. 9
    Answer

    b. Eight characters exist in the str_var. Iterating over all characters and incrementing the value of count variable at each iteration results in the count's value of 8 .

    Concepts in Practice \(\PageIndex{2}\): For loop over a string container

    What's the code's output if the line count += 1 is replaced with count *= 2?

    1. 0
    2. 16
    3. 28
    Answer

    a. Since the initial count's value is 0 , multiplying count by any number results in the output of 0 .

    Concepts in Practice \(\PageIndex{3}\): For loop over a string container

    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()
    Answer

    c. The added line prints each character that is looped on (character c), and prints an additional * after the character.

    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
    )
    Table 5.2
    # 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 \(\PageIndex{4}\): For loop using a range() function

    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)
    Answer

    a. The output will be an increasing sequence between 10 and 22 (inclusive of both): 10 , 13 , 16 , 19 , and 22 .

    Concepts in Practice \(\PageIndex{5}\): For loop using a range() function

    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)
    Answer

    c. The expression starts a sequence from 5 , decreases by 1 at every step, and ends at 1 .

    Concepts in Practice \(\PageIndex{6}\): For loop using a range() function

    What is the sequence generated from range(-1, -2, -1)?

    1. 1
    2. -1, -2
    3. -2
    Answer

    a. The range() function generates a descending sequence, beginning from -1 until -2. Hence, the output is -1.

    Concepts in Practice \(\PageIndex{7}\): For loop using a range() function

    What is the output of the range(1, 2, -1)?

    1. 1
    2. 1, 2
    3. empty sequence
    Answer

    c. When the step size is negative, the generated sequence will be in descending order. Hence, start must be larger than end; otherwise, no sequence will be generated.

    Concepts in Practice \(\PageIndex{8}\): For loop using a range() function

    What is the output of range(5, 2)?

    1. 0, 2, 4
    2. 2, 3, 4
    3. empty sequence
    Answer

    c. When two arguments are provided to the range() function, arguments are considered as start and end of the sequence, and the step size will be 1 . When step size is positive, the generated sequence will be in ascending order, and hence, start must be less than end. Otherwise, no sequence will be generated.

    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.

    Interactive Code
    usr_in = input()
    
    # TODO: counting the number of space characters in usr_in
     
    Input

    This is the input

    Answer

    usr_in = input()

    count = 0
    for c in usr_in:
    if c == ' ':
    count += 1

    print(count)

    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.

    Interactive Code
    n1 = int(input("Enter an integer: "))
    n2 = int(input("Enter another integer larger than the first one: "))
    
    # TODO: printing even numbers in increasing order (inclusive)
    
    # TODO: printing odd numbers in decreasing order (exclusive)
    
     
    Input

    10
    20

    Answer

    n1 = int(input("Enter an integer: "))
    n2 = int(input("Enter another integer larger than the first one: "))

    if n2 <= n1:
    print("Error: n2 must be greater than n1.")
    else:

    # Printing even numbers in increasing order (inclusive)
    if n1%2 == 0:
    for i in range(n1, n2+1, 2):
    print(i, end = ' ')
    else:
    for i in range(n1+1, n2+1, 2):
    print(i, end = ' ')

    print()
    # Printing odd numbers in decreasing order (exclusive)
    if (n2-1)%2 == 1:
    for i in range(n2-1, n1, -2):
    print(i, end = ' ')
    else:
    for i in range(n2-2, n1, -2):
    print(i, end = ' ')


    This page titled 5.2: For Loop is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by OpenStax via source content that was edited to the style and standards of the LibreTexts platform.