Skip to main content
Engineering LibreTexts

5.2: The while Statement

  • Page ID
    8579
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\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}}\)

    Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. Because iteration is so common, Python provides several language features to make it easier.

    One form of iteration in Python is the while statement. Here is a simple program that counts down from five and then says "Blastoff!".

    Code 5.2.1 (Python)
    %%python3
    
    n = 5
    while n > 0:
        print(n)
        n = n - 1
    print('Blastoff!')
    
    

    You can almost read the while statement as if it were English. It means, "while n is greater than 0, display the value of n and then reduce the value of n by 1. When you get to 0, exit the while statement and display the word Blastoff!"

    More formally, here is the flow of execution for a while statement:

    1. Evaluate the condition, yielding True or False.
    2. If the condition is false, exit the while statement and continue execution at the next statement.
    3. If the condition is true, execute the body and then go back to step

    This type of flow is called a loop because the third step loops back around to the top. We call each time we execute the body of the loop an iteration. For the above loop, we would say, "It had five iterations", which means that the body of the loop was executed five times.

    There are two things to remember about while loops:

    • You MUST prime the loop BEFORE you begin the loop. In our example, notice that the value of n is set to 5 BEFORE the loop.
    • Also - there are some 'good ways' and some 'bad ways' to code loops. 

      BOTH of the following pieces of code do the same thing - the first one uses a specific condition in the while. This is the proper way to use a iteration loop.

      The second section of code uses a Boolean 'True', in addition to a 'break' statement in the if block. This is NOT an appropriate method for using a while loop. It is correct, and it works - but it is not the preferred method of coding a loop.

    # Pat
    # CSP 017
    # Loops
    
    myInput = input('Enter a value')
    
    while myInput != 'stop':
         some code goes here...
         # Ask for more input
         myInput = input('Enter another value, or "stop" to quit')
    
    print(Some statement)
    
    # Pat
    # CSP 017
    # Loops
    
    # THIS IS NOT A GOOD WAY TO PROGRAM!!
    while True:
         myInput = input('Enter input')
         if myInput == 'stop'
              break
    
    print(Some statement)
    
    • The body of the loop should change the value of one or more variables so that eventually the condition becomes false and the loop terminates. We call the variable that changes each time the loop executes and controls when the loop finishes the iteration variable. If there is no iteration variable, the loop will repeat forever, resulting in an infinite loop.

    This page titled 5.2: The while Statement is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Chuck Severance.