How can I cumulatively add across python functions?

Viewed 39

I'm trying the below dictionary twice and want to add amounts 10 and 90 , by running the function separately twice. I'm trying the cumulative total which is 100. However, I keep getting 90 as it doesn't remember the value outside my function. I tried making it global variables but to no avail. Thanks

    global new_inventory 
    global inventory
    new_inventory = {}
    def add_fruit(inventory, fruit, quantity=0):    
        if inventory == {}: 
            inventory = {fruit:quantity} 
        elif inventory != {}: 
            inventory = inventory.get(fruit,0)+ quantity
        return inventory
    
    add_fruit(new_inventory,'strawberry',10)
    add_fruit(new_inventory,'strawberry',90)
2 Answers

Altough using the inventory argument inside the function is unnecessary in this specific use-case, to keep add_fruit more dynamic & flexible I'll keep it in anyway.

Therefore you could try:

new_inventory = {}

def add_fruit(inventory, fruit, quantity=0):
    if fruit not in inventory.keys():
        inventory[fruit] = quantity
    else:
        inventory[fruit] += quantity

add_fruit(new_inventory, "strawberry", 10)
add_fruit(new_inventory, "strawberry", 90)

print(new_inventory) # {'strawberry': 100}

Don't reassign inventory in your function, but use methods of it!

Then it'll remain a reference to the same one

def add_fruit(inventory, fruit, quantity=0):
    inventory[fruit] = inventory.get(fruit, 0) + quantity
>>> new_inventory = {}
>>> add_fruit(new_inventory,'strawberry',10)
>>> add_fruit(new_inventory,'strawberry',90)
>>> new_inventory
{'strawberry': 100}

Here's a more complete example of what's happening

>>> def foo(value):
...     print(f"initial value: {id(value)}")
...     value["a"] = 1     # mutate original dict
...     print(f"mutated value: {id(value)}")
...     value = {"b": 2}   # re-use the name for another ref
...     print(f"changed name:  {id(value)}")
... 
>>> input_value = {}
>>> foo(input_value)       # the id() calls show value differs!
initial value: 132972815809856
mutated value: 132972815809856
changed name:  132972815874112
>>> input_value            # only the original reference is changed!
{'a': 1}
Related