[Tutor] Need help with dict.calculation

Andy W toodles@yifan.net
Fri, 25 Jan 2002 12:25:54 +0800


> Well that makes total sense, and I didn't have it defined properly.  Its
> still not working but I'm going
> to continue withit for awhile.  Want thing I do seem to be gifted with
> is persistence.


def gather_data():
  items = raw_input("Add food item: ")
  portion = input("Enter number of portions: ")
  cal_portion = input("Enter calories per portion: ")
  return items,portion,cal_portion

def get_total_calories():
    print "Enter all foods you have eaten today."
    more=""
    total_calories = {}              ## <--- here's the change
    while more != "n":
         items, portion, cal_portion = gather_data()
         total_calories[items] = portion * cal_portion
         more = raw_input("Do you want to continue? y/n: ")
    total=0                      #<--- this bit was missing this time! ;o)
    for i in total_calories.values():
         total = total + i
    print "Total calories: ", total

Let's test it! Hmm I need some fattening up, how about...

>>> get_total_calories()
Enter all foods you have eaten today.
Add food item: Double Whopper with Cheese
Enter number of portions: 1
Enter calories per portion: 960
Do you want to continue? y/n: y
Add food item: Chinese Chicken Salad Large
Enter number of portions: 1
Enter calories per portion: 191
Do you want to continue? y/n: n
Total calories:  1151
>>> 

Looks like it's working!

Andy