Skip to main content
Engineering LibreTexts

5.1: While Loop

  • Page ID
    117549
  • \( \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 loop construct in Python.
    • Use a while loop to implement repeating tasks.

    While loop

    A while loop is a code construct that runs a set of statements, known as the loop body, while a given condition, known as the loop expression, is true. At each iteration, once the loop statement is executed, the loop expression is evaluated again.

    • If true, the loop body will execute at least one more time (also called looping or iterating one more time).
    • If false, the loop's execution will terminate and the next statement after the loop body will execute.
    Checkpoint: While loop
    Concepts in Practice: While loop example

    Fibonacci is a series of numbers in which each number is the sum of the two preceding numbers. The Fibonacci sequence starts with two ones: 1, 1, 2, 3, . . . . Consider the following code that prints all Fibonacci numbers less than 20, and answer the following questions.

        # Initializing the first two Fibonacci numbers
        f = 1
        g = 1
        print (f, end = ' ')
    
        # Running the loop while the last Fibonacci number is less than 20
        while g < 20:
          print(g, end = ' ')
          # Calculating the next Fibonacci number and updating the last two sequence numbers
          temp = f
          f = g
          g = temp + g
    
    Concepts in Practice \(\PageIndex{1}\): While loop example

    How many times does the loop execute?

    1. 5
    2. 6
    3. 7
    Answer

    b. The loop runs six times for values of g = 1 , 2 , 3 , 5 , 8 , and 13 .

    Concepts in Practice \(\PageIndex{2}\): While loop example

    What is the variable g's value when the while loop condition evaluates to False?

    1. 13
    2. 20
    3. 21
    Answer

    c. 21 is the first Fibonacci number larger than 20, and for g = 21, the condition will evaluate to False for the first time.

    Concepts in Practice \(\PageIndex{3}\): While loop example

    What are the printed values in the output?

    1. 1 1 2 3 5 8 13
    2. 1 2 3 5 8 13
    3. 1 1 2 3 5 8 13 21
    Answer

    a. The code first prints the variable f's initial value. Then, at each iteration, g's value is printed, and g's value throughout the code's execution will be 1 , 2 , 3 , 5 , 8 , and 13 . Thus, all printed values are 1 , 1 , 2 , 3 , 5 , 8 , and 13 .

    Counting with a while loop

    A while loop can be used to count up or down. A counter variable can be used in the loop expression to determine the number of iterations executed. Ex: A programmer may want to print all even numbers between 1 and 20. The task can be done by using a counter initialized with 1. In each iteration, the counter's value is increased by one, and a condition can check whether the counter's value is an even number or not. The change in the counter's value in each iteration is called the step size. The step size can be any positive or negative value. If the step size is a positive number, the counter counts in ascending order, and if the step size is a negative number, the counter counts in descending order.

    Example 5.1: A program printing all odd numbers between 1 and 10
        # Initialization
        counter = 1
    
        # While loop condition
        while counter <= 10:
          if counter % 2 == 1:
            print(counter)
          # Counting up and increasing counter's value by 1 in each iteration
          counter += 1
    Checkpoint: Counting with while loop
    Concepts in Practice: while loop counting examples

    Given the code, answer the following questions.

        n = 4
        while n > 0:
          print(n)
          n = n - 1
        
        print("value of n after the loop is", n)
    
    Concepts in Practice \(\PageIndex{4}\): while loop counting examples

    How many times does the loop execute?

    1. 3
    2. 4
    3. 5
    Answer

    b. The loop runs for n = 4, 3 , 2 , 1 . 5

    Concepts in Practice \(\PageIndex{5}\): while loop counting examples

    Which line is printed as the last line of output?

    1. value of n after the loop is -1.
    2. value of n after the loop is 0.
    3. value of n after the loop is 1.
    Answer

    b. The loop's termination condition is n = 0; therefore, the value of n after the loop equals 0 . The last printed line will be: value of n after the loop is 0.

    Concepts in Practice \(\PageIndex{6}\): while loop counting examples

    What happens if the code is changed as follows?

    n = 4
    while n > 0:
      print(n)
      # Modified line
      n = n + 1
    
    print("value of n after the loop is", n)
    
    1. The code will not run.
    2. The code will run for one additional iteration.
    3. The code will never terminate.
    Answer

    c. Since the initialization value for n equals 4 and the value of n is only increasing, the loop condition will always remain true. The loop will never terminate.

    Try It: Reading inputs in a while loop

    Write a program that takes user inputs in a while loop until the user enters "begin". Test the code with the given input values to check that the loop does not terminate until the input is "begin". Once the input "begin" is received, print "The while loop condition has been met.".

    Enter different input words to see when the while loop condition is met.

    Interactive Code
    usr = input()
    
    # Printing the given input
    print("You have entered", usr)
    
    # TODO: while statement
    
    
    
    
     
    Input

    Time
    to
    begin

    Answer

    usr = input()
    print("You have entered", usr)

    # While statement
    while usr != "begin":
    usr = input()
    # Printing the given input
    print("You have entered:", usr)

    print("The while loop condition has been met.")

    Try It: Sum of odd numbers

    Write a program that reads two integer values, n1 and n2. Use a while loop to calculate the sum of odd numbers between n1 and n2 (inclusive of n1 and n2). Remember, a number is odd if number % 2 != 0.

    Interactive Code
    n1 = int(input("Enter an integer: "))
    n2 = int(input("Enter another integer: "))
    
    # TODO: while statement
    
     
    Input

    10
    20

    Answer

    n1 = int(input("Enter an integer: "))
    n2 = int(input("Enter another integer: "))

    index = n1
    total = 0
    while index <= n2:
    if index % 2 != 0:
    total += index
    index += 1

    print(total)


    This page titled 5.1: While 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.