Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I cumulatively add across python functions?

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)

”’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading