Home > OS >  How can I cumulatively add across python functions?
How can I cumulatively add across python functions?

Time:03-28

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)

'''

CodePudding user response:

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

    return inventory

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

print(new_inventory)

CodePudding user response:

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}
  • Related