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)
”’
>Solution :
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}