4-digit sum - WHY did this work?


#1

I've just completed the '4-digit sum' challenge exercise (URL immediately below), & I've just realized that I don't understand why the 'for loop' line of my code was successful.

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

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

Because it did work, I conclude that it functioned in a manner similar to 'for each letter in word:' - but in previous attempts at this, the exact same line returned a 'int is not iterable' error instead, which I understand to mean that it was recognizing the argument as a single (value? string?) rather than "x number of characters in a string".

I guess my question is ultimately "How can I recognize/tell the difference when Python will parse individual characters from a string versus when it's going to see the string itself as the argument??'

Finally, THANK YOU for this AWESOME resource!!!


#2

A string is a sequence, you can iterate over it
An integer isn't a sequence, so you can't iterate over it

There's no mystery here, other than perhaps losing track of what your variables refer to


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.