Python Forum
How to Think Like a Computer Scientist - Iteration Problem
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to Think Like a Computer Scientist - Iteration Problem
#1
Please see http://interactivepython.org/runestone/s...nel-values

This is the code given.. (This might remove the idents - see the website if this happens)

def checkout():
total = 0
count = 0
moreItems = True
while moreItems:
price = float(input('Enter price of item (0 when done): '))
if price != 0:
count = count + 1
total = total + price
print('Subtotal: $', total)
else:
moreItems = False
average = total / count
print('Total items:', count)
print('Total $', total)
print('Average price per item: $', average)

checkout()

On the site underneath the code it states

"If you enter zero the first time you are asked for a price, the loop will end, and the program will try to divide by zero. Use an 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."

Haven't been able to work this out - a seemingly simple if/else statement outside of the loop to catch the divide by zero. Any help gratefully received. Many thanks Tom
Reply


Messages In This Thread
How to Think Like a Computer Scientist - Iteration Problem - by rubicana - Sep-07-2017, 11:43 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  list call problem in generator function using iteration and recursive calls postta 1 2,047 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  python result problem of an iteration algorithm for power allocation Jessica 1 2,795 Sep-07-2018, 08:08 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020