Note 5.3.1.
We’ve done something new in line three. Instead of writing two lines of code:
years_str = input("Enter your age in years: ")
years = int(years_str)
we combine them into one statement by nesting the function calls.
while
while
in Section 5.2 was used to count from one to six. In addition to doing counting with while
, we normally use a while
loop when we don’t know in advance how many times a loop will execute. The last program on that page didn’t do any counting; it continued until the loop condition came back False
. That program was a good example of an example, but not a particularly useful program.years_str = input("Enter your age in years: ")
years = int(years_str)
total
to zero.number_of_items
to zero.price
to None
to indicate that it has never been used yet.price
is not 0:price
and convert to float
.price
is not 0:number_of_items
price
to total
.average_price
as total
divided by number_of_items
number_of_items
, total
, and average_price
, properly labeled.total = 0.0
number_of_items = 0
price = None
while price != 0:
price = float(input("Enter price, or 0 when finished: "))
if price != 0:
number_of_items = number_of_items + 1
total = total + price
average_price = total / number_of_items
print("Number of items:", number_of_items)
print("Total cost: $", total)
print("Average price: $", average_price)
elif
is your friend.if
/else
statement outside the loop to avoid the division by zero and tell the user that you can’t compute an average without data.