[Tutor] Need help with dict.calculation
Andy W
toodles@yifan.net
Sat, 19 Jan 2002 18:43:53 +0800
Hi Eve,
I won't make changes that are _too_ drastic, but I suggest you divide tasks
into separate functions.
At the moment it's recursive, and I don't think that's very useful here. (It
could work, but I just don't think it's necessary).
The first function will gather the data, the second will do the
looping/control.
This is all untested, but it should give you some ideas.
> In the script below I would like to add up the totals for each item into
> one final total. So far I haven't come up with anything. Help.
#
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=""
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: ")
for i in total_calories.values():
total = total + i
print "Total calories: ",total
#
As a side note, you don't even need to put it in a dictionary, you can just
have a running total in an integer variable.
I said I wouldn't make drastic changes though :o)
Andy
>
> def food_add():
> print "Enter all foods you have eaten today."
>
> items = raw_input("Add Food Item: ")
> portion = input("Enter number of portions: ")
> cal_portion = input("Enter calories per portion: ")
>
> more = raw_input("Do you wish to continue? y/n: ")
> while more != 'n':
> food_add()
> break
> total_calories[items] = portion * cal_portion
> total = 0
> for i in total_calories.values():
> total = total + i
> print "Total calories: ",total
>
> My output is:
>
> Total calories: 120
> Total calories: 254
>
> The total calories for each item entered with the last entry first,
> rather than just a Total calories: 374
> --
>
> ekotyk
>
> http://members.shaw.ca/e.kotyk/virtualstudio.htm
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>