In the last lecture from “Introduction to Python” exercise which involves the dictionaries, I tried to use the following:
I want the following code to give the total price when use call the function with the price being equal or less that the parameter. However the output should be 74 and it is give me 50, being the exact same as the lasagna. How can I change the code to give me a output in this case of 74 being all prices below or equal to the parameter 5?
prices = {
“box_of_spaghetti” : 4,
“lasagna” : 5,
“hamburger” : 2
}
quantity = {
“box_of_spaghetti” : 6,
“lasagna” : 10,
“hamburger” : 0
}
money_spent = 0
def Price_while(Price):
money_spent = 0
for item in prices:
while Price <= prices[item]:
money_spent += (prices[item] * quantity[item])
return money_spent
Price_while(5)
Output: 50
Hi Andre!
Thanks for reaching out.
This Python function returns a single value. So, if you execute Price_while(5), you will be referring to the “lasagna” as you say. It is the only meal whose price is greater than or equal to 5, therefore we have 5*10=50 currency units spent.
Then, if you execute Price_while(4), you will be referring to the price spent for a box of spaghetti, which will be 4*6=24.
To obtain the result from the lecture, please use the code provided there. Thank you.
Hope this helps but please feel free to get back to us should you need further assistance. Thank you.
Best,
Martin
Hi Martin. Thanks for the reply. I manage to obtain and understand the exercise, however the code in the exercise it is storing the value under “money_spent”, so every time you run it another “print(money_spent)” that will be adding to the new “print(money_spent)”, e.g. first question is printing 50 (correct) but then if I want to find the money_spent for another value I have to run the dictionary again or attribute the value “zero” to “money_spent”. I was just trying to figure it out how I can do it, without adding the previous output everytime I run the “print(money_spent)”. I guess I try to do too much with the knowledge I had at the time. I could achieve the result by creating an “input” I think. Thanks.
Hi Andre! Please accept my apologies for the delayed response. Yes, exactly! This is just how we wanted this loop to work. Thank you for sharing this with the Community! Good luck and please feel free to post another question should you encounter any other difficulties. Thank you.
Best,
Martin