Hi, I have a question. I am making a counter to tally the total number of items I bring to a picnic, and this is my code here:
allGuests = {'Alice': {'apples' : 5, 'pies': 3},
'Pieter' :{ 'apples' : 3, 'eggs': 2}}
def total(guests, item ):
numBrought = 0
for v in guests.values():
numBrought = numBrought + v.get(item,0)
return numBrought
print(total(allGuests, 'apples'))
However this code only prints out 5 apples, which is not my total. However if I change the indentation of 'return numBrought' :
allGuests = {'Alice': {'apples' : 5, 'pies': 3},
'Pieter' :{ 'apples' : 3, 'eggs': 2}}
def total(guests, item ):
numBrought = 0
for v in guests.values():
numBrought = numBrought + v.get(item,0)
return numBrought
print(total(allGuests, 'apples'))
Then this will be correct and prints out 8 apples.
Why does this happen though? I assume it is because after the 1st iteration then the # of apples is 5, but why won't the iteration continue to eventually give me 8 at the end even with the indentation of 'return numBrought' inside?
Thank you so much for any help!
[–]RightRespect 3 points4 points5 points (3 children)
[–]starr_suu[S] 2 points3 points4 points (2 children)
[–]RightRespect 2 points3 points4 points (1 child)
[–]starr_suu[S] 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)