Lecture 6

Practice with if Statements

An internet service provider has three subscription packages for customers to choose from:

  1. Package A: For $9.95 per month, 10 hours of access are provided. Additional hours are $2.00 per hour.
  2. Package B: For $13.95 per month, 20 hours of access are provided. Additional hours are $1.00 per hour.
  3. Package C: For $19.95 per month, access is unlimited.

Write a program that calculates a customer's monthly bill. It must ask the user to enter the letter of the package they purchased (A, B, C) and the number of hours they used (the user does not have to enter a whole number). It should then display the total charges (formatted to look like a dollar amount).

If the user does not give you a valid subscription package (capitalization does not matter), tell them. If the number of hours they used is not positive, tell them.

Here is an example of what your program should look like when it runs (what the user types is in bold underline):

What package have you subscribed to? a
How many hours did you use? 13
Your total charge is $15.95.

Here is the start of the program:

package = input("What package have you subscribed to? ")
package = package.lower() #why is this done?

hours = input("How many hours did you use? ")
hours = float(hours) #why is this done?

#what does the rest of the program look like?

while Loops

while loops are like if statements that repeat while the condition is True. The while loop looks like: while condition:
    #statements to execute while condition is True

The while loop starts with the Python keyword "while". What follows is the "condition" (a Boolean expression), then a colon. This can be called the while loop header. On the next line, you begin the body of the while loop. Each line of the body must be indented (a tab or four spaces is standard). The body consists of statements to execute while the condition is True. The first non-indented line ends the body. Here is an example:

#This program calculates a sales commission

#calculate a series of commissions
keep_going = 'y'
while keep_going[0].lower() == 'y':
    sales = float(input('Enter the amount of sales: '))
    comm_rate = float(input('Enter the commission rate: '))
    
    commission = sales * comm_rate
    
    print('The commission is $'+format(commission, '.2f'))
    
    keep_going = input('Do you want to calculate another commission? ')

When the program first encounters the while loop, it evaluates the condition. If the condition is True, then the body of the while loop executes. At the end of the body, the program jumps back to the top of the while loop and evaluates the condition again. If it's still True, then it executes the body again. This continues until the condition is false.

What happens if that last line in the while loop body wasn't there? In other words, what happens if the code were:

#This program calculates a sales commission

#calculate a series of commissions
keep_going = 'y'
while keep_going[0].lower() == 'y':
    sales = float(input('Enter the amount of sales: '))
    comm_rate = float(input('Enter the commission rate: '))
    
    commission = sales * comm_rate
    
    print('The commission is $'+format(commission, '.2f'))

Why do you think we needed to set keep_going to 'y' before we started the while loop? In other words, what happens if the code were:

#This program calculates a sales commission

#calculate a series of commissions
while keep_going[0].lower() == 'y':
    sales = float(input('Enter the amount of sales: '))
    comm_rate = float(input('Enter the commission rate: '))
    
    commission = sales * comm_rate
    
    print('The commission is $'+format(commission, '.2f'))
    
    keep_going = input('Do you want to calculate another commission? ')

What happens if keep_going were set to something else before the while loop started? For example:

#This program calculates a sales commission

#calculate a series of commissions
keep_going = 'sure'
while keep_going[0].lower() == 'y':
    sales = float(input('Enter the amount of sales: '))
    comm_rate = float(input('Enter the commission rate: '))
    
    commission = sales * comm_rate
    
    print('The commission is $'+format(commission, '.2f'))
    
    keep_going = input('Do you want to calculate another commission? ')

What values are invalid in the program above? How should we handle them?

Sentinel Values

In the programs above, the user has to enter three values each time through the loop. Sentinel values are a convenient way to remove the "do you want to repeat?" question. Basically, a sentinel value is a special value that would normally be considered invalid, but can instead be used to indicate that the user wants to stop. For example, in the example above a negative sales amount should be considered invalid, but maybe we can say that -1 means the user wants to stop the loop:

#This program calculates a sales commission

#calculate a series of commissions
sales = float(input('Enter the amount of sales (or -1 to stop): '))
while sales != -1:
    comm_rate = float(input('Enter the commission rate: '))
    
    commission = sales * comm_rate
    
    print('The commission is $'+format(commission, '.2f'))
    
    sales = float(input('Enter the amount of sales (or -1 to stop): '))

Notice that the condition for the while loop changed, the sales amount prompt changed, and the prompt was moved around. Why do you think each change was made?

Input Validation

while loops can be used for input validation. The program below asks the user for a number. It then computes the square root of that number and displays the result.

from math import sqrt
num = float(input("Enter a number: "))

sr_num = sqrt(num)
print("The square root of", num, "is", sr_num)

One problem with this program is that it crashes on negative numbers. Before while loops, the best we could do was detect the negative number and stop the program, i.e.:

from math import sqrt
import sys #needed to end program

num = float(input("Enter a number: "))

if num < 0:
    print("Only the square root of positive numbers can be calculated")
    sys.exit()

sr_num = sqrt(num)
print("The square root of", num, "is", sr_num)

Now that we've seen while loops, we can ask again instead of ending the program:

from math import sqrt

num = float(input("Enter a number: "))
while num < 0:
    print("Only the square root of positive numbers can be calculated")
    num = float(input("Enter a number: "))

sr_num = sqrt(num)
print("The square root of", num, "is", sr_num)

Infinite Loops

Infinite loops are loops that never stop, i.e. the condition is never False. There are two common reasons for this:

  1. forgetting to update variables in the condition
  2. updating variables in the wrong direction

Forgetting to Update Variables in the Condition

A very simple example is:

count = 0
while count <= 25:
    print("count =", count)

We saw another example of this above.

Updating Variables in the Wrong Direction

A very simple example is:

count = 0
while count <= 25:
    print("count =", count)
    count -= 1

Nested Loops

Just like nested if statements, it is possible to nest loops inside of other loops. For each time through the outer loop, the inner loop loops completely:

hours = 0
while hours < 25:
    minutes = 0
    while minutes < 60:
        print(hours, ':', minutes, sep='')
        minutes += 1
    hours += 1

Why do you think minutes is set to zero inside the first while loop? Why isn't it:

hours = 0
minutes = 0 #minutes set to zero outside the first while loop, in contrast to above
while hours < 25:
    while minutes < 60:
        print(hours, ':', minutes, sep='')
        minutes += 1
    hours += 1

Accumulator Variable

A accumulator variable is simply a variable that gathers, collects, or accumulates values during execution of a loop. In the example below, it will accumulate numbers as a running total. However, accumulator variables are just like any other variable, but with a special purpose: accumulating values. In addition to numbers, accumulators are also often strings or lists (called arrays in other languages ... more on these soon).

Here's an example of an accumulator variable. It sums up all the non-zero numbers the user enters, then displays the average. Note the use of a sentinel value to stop the loop.

total = 0
count = 0
num = float(input("Enter a number (or zero to stop): "))

while num != 0:
    total += num
    count += 1
    num = float(input("Enter a number (or zero to stop): "))

avg = total / count
print("The average of the numbers you entered is:", avg)
<< Previous Notes Daily Schedule Next Notes >>