A problem about range() in Digit_Sum


#1



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


By running my code, the python returned this warning: TypeError: 'int' object has no attribute 'getitem'


What's wrong with my code?
And when I ran the sum() to add two int(), it returned TypeError: 'int' object is not iterable. What does it mean?

def digit_sum(n):
    for i in range(len(str(n))):
        print sum(n[i])        

digit_sum(123)

#Why can't sum() add two int()? and why the warning was different?

print sum(int(1)+int(3))


#2

just like you would do in math, to add two integers together we can use plus (+)

sum() is a built in function to calculate the sum of an iterable (like a list)


#3

The reason was that n was an integer and int[ ] was illegal. Thank you anyway.


#4

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