4. Digit_Sum


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096#


In the first section of code, it returns 3 instead of the sum of the digits. The second section of code returns the correct sum.

Why? What's the difference?

I guess if someone could answer the following, it would help explain what's going on to me:

What's the difference between 'for i in range()' and 'for item in list'? From what I understand, the first one loops by index whereas the other does 'for item' does not? Something about this jogs my memory from some previous lessons (don't remember number exactly) but it said that using the 'for x in list' method cannot modify every element in a list, whereas using the 'for i in range()' can because it loops by index? Does that sound familiar?

Could someone explain these two concepts to me?


def digit_sum(n):
    total = 0
    n = str(n)
    for i in range(0,len(n)):
        total = total + int(i)
    return total


-----------------------

def digit_sum(n):
    total = 0
    n = str(n)
    for i in range(0,len(n)):
        total = total + int(n[i])
    return total


#2

there is a quit a difference there, lets say i have this list:

aList = [4,3,4]

then using:

for x in aList:

would give me the numbers in the list, which we can see if we add a print statement:

for x in aList:
   print x

where as range would give me the indexes, which we can use to access the specific item at that index (which also allows us to manipulate the list):

for x in range(0,len(aList)):
   print x, aList[x]

Does that help?


#3

The reason why the first function prints only 3 is because i only gives you the index (which is a number). It didn't access the list using the index as indicated in int(i). It basically made the index an integer and I assume the list had 3 elements so you basically added 0 + 1 + 2 == 3 (since index start at 0).

The second function does access the list using the index as indicated, int(n[i]) and so you are adding the numbers in the list according to the index they are in.

So, let's say your list is n = [2, 3, 4], int(i) will produce the following numbers: 0, 1, and 2 as that is the indexes for that list in that range (0-3 not including 3). Hence, your total will add those numbers produced.
For int(n[i]), it access the list using the index so whatever is in index 0 (which is 2) gets accumulated in the total (2 + 3 + 4 == 9). And you continue with that until the index reaches the length of the list.


#4

I think so, I'll have to logic it out in my head but yeah, thank!


#5

I think that makes sense. I think I need to play around with it and get the logic behind it. Thanks!