Issue calling the bill function in Stocking_


#1

shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}
    
prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

# Write your code below!
def compute_bill(food):
    total = 0
    for item in food:
        if stock[item] > 0:
            total += prices[item] 
            stock[item] -= 1 
            print stock[item] '''This does not output anything in the console, why?'''
    return total
    
print compute_bill(shopping_list) '''When I try this, I get: "stock doesn't look quite right! Make sure to not call compute_bill since it changes the stock! It should contain: {'orange': 32, 'pear': 15, 'banana': 6, 'apple': 0}". Why? Also, the output of the calculation is 5.5 in the console which I don't understand. Yet removing just this line allows me to progress to the next lesson. Any explanation would be appreciated.'''

Some of the issue I have have been noted directly on the corresponding lines of code. I know I don't need to call the compute_bill() but I would really like to understand why it is not working and what this function is doing. Does it actually change the stock outside of the function permanently? If so how could I avoid that?


#2

In a word, yes. The dictionaries exists outside of the function and are in parent (global) scope. Even passed in as arguments, since they are reference objects they would not be local to the function. Only their reference variable would be. Either way, as parameter or parent reference, the effect on the object is the same, uniformly.


#3