Skip to main content
Chemistry LibreTexts

2.7: Looping Structures – WHILE Loops

  • Page ID
    206265
  • hypothes.is tag: s20iostpy07ualr 
    Download Assignment S2020py07

     

    Learning Objectives

    Students will be able to:

    Content:

    • Explain the three parts of a loop
    • Explain the syntax of a while loop
    • Explain sentinel-controlled and counter controlled loops
    • Explain short-cut operators

    Process:

    • Write code that includes sentinel-controlled and counter controlled loops
    • Write code that uses short-cut operators

    Prior Knowledge

    • Python concepts from Activities 1-6
    • Understanding of flowchart input symbols

    Further Reading

     

    Model 1: While loops

    A looping structure allows a block of code to be repeated one or more times. A while loop is one of the two looping structures available in Python

    Python Program 1

    Output

    # Description: This program prints a message 
    # stored in a variable 10 times
    message1 = "Outside of loop." 
    message2 = "I am in a while loop."
    counter = 0
    print(message1)
    while(counter < 10):
        print(message2)
        counter = counter + 1
    print(message1)
    

     

    Outside of loop.

    I am in a while loop.

    I am in a while loop.

    I am in a while loop.

    I am in a while loop.

    I am in a while loop.

    I am in a while loop.

    I am in a while loop.

    I am in a while loop.

    I am in a while loop.

    I am in a while loop.

    Outside of loop.

    Critical Thinking Questions

    1.   Closely examine the flowchart and Python program in Model 1.

    1. In the Python code, circle all the code associated with the WHILE loop.
    2. Enter and test the code. What does the line of code: counter = counter +1 do?                     
    3.  How does the Python interpreter know what lines of code belong to the loop body?
    4. Every loop structure requires three actions. In the space below, write the line of code in the Python program that corresponds to each of the three actions.
    • Initialize a variable used in the test condition:
    • Include a test condition that causes the loop to end when the condition is false:
    • Within the loop body, update the variable used in the test condition:   

    2.   Enter and execute the following code using input values where number

    • number <10
    • 10< number < 20
    • number=20
    • 20< number < 30
    • Number > 3

     

    Python Program 2

    # Description: This program prints
    # numbers from 1 to the value
    # entered by a user
    
    number = int(input("Enter a number: "))
    x = 1
    while(x <= number):
        if(x % 10 == 0):
            print(x)
        else:
            print(x, end = " ")
        x = x + 1
    

                a.  Beside each line of code above explain what the code does.
                b.  How do you change a print statement so that it does not signal the computer to write on a new line?

    3.  The following code should print the numbers from 1 to 10, but it does not print anything.  Correct the problem

    Python Program 3

    number = 12
    while number <= 10:
    	print(number)
    	number = number + 1
    
    

     

    4.   Enter and execute the following code:

    Python Program 4

    number = 0
    while number <= 10:
    	print(number)
    	number = number - 1
    
    

     

    thonny interface

    NOTE: <ctrl + c> will cause a "Keyboard Interrupt" and stop a runaway program, as will the stop sign on the Thonny Interface

    5.   Enter and execute the following code:

    Python Program 5

    number = 1
    while number <= 10:
        if number % 2 == 0:
            print(number, end= "  ")
        number = number + 1
    
    

     

    1. State the output.
    2. What caused the output to display on one line?
    3. What two control structures are used in this code?           


    6.  The following directions will create a program that prompts the user to enter a number between 1 and 10. As long as the number is out of range the program re-prompts the user for a valid number. Complete the following steps to write this code.

    1. Write a line of code the prompts the user for number between 1 and 10.
    2. Write a Boolean expression that tests the number the user entered by the code in step “a.” to determine if it is not in range.
    3. Use the Boolean expression created in step “b.” to write a while loop that executes when the user input is out of range.  The body of the loop should tell the user that they entered an invalid number and prompt them for a valid number again.
    4. Write a line of code that prints a message telling the user that they entered a valid number.
    5. Put the segments of code from steps “a-d” together. Enter and execute the code. Does it work properly?  If not, correct it and test it again.
    6. How many times does the loop execute?

    Note

    A looping structure for which you know the number of times it will execute is known as a count-controlled loop.  In a sentinel-controlled loop there is a "signal" or "flag" value that tells the loop to end, and so you do not know how many times it will loop. 

    7.  Sometimes a programmer does not know how many times data is to be entered. For example, suppose you want to create a program that adds an unknown amount of positive numbers that will be entered by the user. The program stops adding numbers when the user enters a zero or a negative number. Then the program prints the total. Before creating this program, review the three actions required for all loops:

    1. Initialize a variable that will be used in the test condition: 
      What will be tested to determine if the loop is executed or not?  Write a line of code that initializes a variable to be used in the test condition of the loop for this program. The variable should contain a value entered by the user.
    2. Include a test condition that causes the loop to end when the condition is false: 
      What is the test condition for the while loop used in this program?
    3. Within the loop body, update the variable used in the test condition: 
      Write the code for the loop body. Include the code to update the variable in the test condition.
    4. Is this a count-controlled loop?
      Why or why not?
    5. Complete the program. 
      Enter and execute the code.
    NOTE: Short-cut operators provide a concise way of creating assignment statements when the variable on the left-hand side of the assignment statement is also on the right-hand side. The addition short-cut operator  i(+=) is usually used for incrementing a variable.

    8. Enter and execute the following code:

    Python Program 6

    number = 1
    number += 3
    print(number)
    
    

     

     

    1. What does the “+=” shortcut operator do?
    2. The code: x += 5 is equivalent to which of the following lines of code?
    • x = 5
    • x = y + 5
    • x = x + 5
    • y = x + 5

     

         c.   Replace the operator ‘+=’ with the following shortcut operators and execute the code.   Explain what each operator does.

    • -=
    • *=

    9.   Enter and execute the following code:

    Python Program 7

    #go to questions "a" & "b" after running this code
    bonus = 25
    salary += bonus
    print("Total salary:", salary)
    

     

           a.   What is the output of the preceding code? Is it what you expected?

           b.   Rewrite the code so that it produces valid output.

           c.         Is the following line of code valid:  23 += total?  Why or why not?

     

    10.    The following code should print the numbers beginning with 100 and ending with 0. However it is missing a line of code. Write the line of missing code using the shortcut operator so the program works.

    Python Program 8

    countdown = 100
    while countdown > 0:
        print(countdown)
    print("Done!")
    
    
    

     

    11.  Enter and execute the following code:

    Python Program 9

    doAgain = "y"
    while doAgain == "y":
       word = input("Enter a word:")
       print("First letter of " + word  + " is " + word[0])
       doAgain = input("Type ‘y’ to enter another word and anything else to quit.")
    print("Done!")
    
    
    

     

         a.   What does the program do?

         b.   What is the variable used to store the user’s input?

         c.   In the print statement, what does word[0]represent?

         d.   If you changed 0 to 1 in word[0]in the print statement above, what do you think will be printed?

         e.   When does the program end?

         g.   Why do you think this the loop in this program is an example of a sentinel control  loop?

         h.   Examine the print statement in this program:

                print("First letter of " + word  + " is " + word[0])

     

    What is the purpose of the “+” as part of the argument in the print statement? How would the output change if you replace each “+” with a “,”

    Information: 

    A variable that can store only the values True and False is called a Boolean variable. The type() function can be used to tell you what class (Boolean, integer, floating point, or string) of data is stored in a variable

    12.     Examine the code below.

          name = "Simone"
          cost = 3.56

          numApples = 89

          foundCost = False

     

    What class of data is stored in each variable: (Boolean, integer, floating point, or string)

      • name –
      • cost –
      • numApples –
      • foundCost –
    NOTE:  To check your answers above, you can type each of the variables into your python shell, and then use the type() function to identify the class of data.

    13. Interpret the following code:
    python code

         a.    What does the program do?

         b.   What type of variable is ‘doAgain’?

         c.   What does the following code in the program do?
                    if another != 'y':
               doAgain = False
    CopyRight Statement

    cc4.0
    This work  is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License, this material is a modification by Ehren Bucholtz and Robert Belford of CS-POGIL content, with the original material developed by Lisa Olivieri, which is available here.


    Application Questions: Use the Python Interpreter to check your work

    1.         Write a code segment that prompts the user for an even number. As long as the number is not even, the user should be given a message and prompted again for an even number.

    2.         Write code segment that prompts the user for a letter from ‘a-z’. As long as the character is not between ‘a-z’, the user should be given a message and prompted again for a letter between ‘a-z’.