ThatDaven
ThatDaven

Reputation: 27

How to incorporate a price finder?

print('How many items are you planning to buy?')
times = int(input('>> '))
def question(times):
 grocery_list = {}
 print('Enter grocery item and price.')
 for i in range(times):
  key = input('Item %d Name: ' % int(i+1))
  value = input('Item %d Price: $' % int(i+1))
  print
  grocery_list[key] = value
  print(grocery_list)
question(times)
print('<                    >')

In this code I've made for a shopping list, there is a problem... I couldn't find a way to incorporate all of the items in the list's price. I want to compute the sum of all item prices on the list. Any help on that? This has totally confused me and I don't want to make an individual variable for each item. Thank you.

Upvotes: 0

Views: 129

Answers (1)

Stefan Scheller
Stefan Scheller

Reputation: 953

Do you want to compute the sum of all item prices on the list? Then adding these two lines after the loop in your question function should work:

totalPrice = sum([float(grocery_list[item]) for item in grocery_list])
print('Total: ${:.2f}'.format(totalPrice))

Or as complete, reformatted code:

print ('How many items are you planning to buy?')
times = int(input('>> '))

def question(times):
    grocery_list = {}
    print ('Enter grocery item and price.')
    for i in range(times):
        key = input('Item %d Name: ' % int(i+1))
        value = input('Item %d Price: $' % int(i+1))
        grocery_list[key] = value
        print(grocery_list)
    totalPrice = sum([float(grocery_list[item]) for item in grocery_list])
    print('Total: ${:.2f}'.format(totalPrice))

question(times)
print('<                    >')

Update

Here is an alternative implementation for a grocery list using a list as container and adding quantities to the items:

def inputGroceries():
    groceries = list()
    while True:
        try:
            i = len(groceries)
            name = input('Item #{} name: '.format(i))
            if name == '':
                break
            price = float(input('Item #{} price: $'.format(i)))
            quantity = int(input('Item #{} quantity: '.format(i)))
        except ValueError:
            print('Error: invalid input..')
            continue
        groceries.append((name, price, quantity))
    return groceries

print("Enter items, price and quantity (end list by entering empty name):")
groceries = inputGroceries()

for item in groceries:
    print('{} x {} (${:.2f} PP)'.format(item[2], item[0], item[1]))

totalPrice = sum([item[1] * item[2] for item in groceries])
print(30*'-')
print('Total: ${:>22.2f}'.format(totalPrice))

Input/ Output looks like this:

Enter items, price and quantity (end list by entering empty name):
Item #0 name: beer
Item #0 price: $1 
Item #0 quantity: 6
Item #1 name: apple
Item #1 price: $0.5
Item #1 quantity: 2
Item #2 name: 
6 x beer ($1.00 PP)
2 x apple ($0.50 PP)
------------------------------
Total: $                  7.00

Upvotes: 2

Related Questions