11/10 Making a Purchase


No problem here, just wondering why we have the total=0 in this code

def sum(numbers):
    total = 0
    for number in numbers:
        total += number
    return total
n = [1, 2, 5, 10, 13]
print sum(n)


Whenever you sum some things in real life, you initially start empty handed (= zero). Then as you keep coming across numbers, you keep adding them to your existing sum. So, if you had to numbers 10, 11, 12, 13 in real life, you would:

  1. State that currently your sum is zero
  2. Take one number from the list
  3. Add it to your sum
  4. Repeat 2 & 3 till no numbers are left.

Hopefully, you now understand why we need to take total = 0 :smile: , if you don't, I can explain you again.


Thanks a lot :smile:


2 posts were split to a new topic: Getting error: "'return' outside function"


That's initialization, which means that you are just giving your variable an initial value which, in this case, is 0. This is done so that the variable doesn't have any garbage value while it is being used.


It doesn't quite work..


@geraldosmenaj Could you explain clearly what you mean? Thanks!


@gaurangtandon I got it now, thanks.