Your code threw a "'int' object has no attribute '__getitem__'" error


#1

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

When attempting the digit_sum exercise in practice makes perfect, I get the following error: Oops, try again. Does your digit_sum function take exactly one argument (a positive integer)? Your code threw a "'int' object has no attribute 'getitem'" error.

Please see my code below (which appears to work in pycharm):


I do not understand why I get the error in codeacademy and not in pycharm. Is my code incorrect?


# Function to add components of a number e.g. 1234 = 10
def digit_sum(n):
    list = []
    list_tot = 0
    for i in range (len(str(n))):
        list.append(int(n[i]))
        list_tot = list_tot + list[i]
    return list_tot

numb_txt = raw_input('Enter a positive number: ')

print digit_sum(numb_txt)


#2

the problem is that the exercise of codecademy checks your function using integers, raw_input gives you a unicode

i think i get it now, the problem is in this line:

list.append(int(n[i]))

when n is a unicode, it behaves like a string, you can use indexes, this doesn't work for integers. (when the exercise calls the function, it passes a integer as argument)

this is possible: "3"[0] # access index 0 of string/unicode
this isn't: 3[0] # trying to access index of integer

you could simply cast n to a string on the problem line


#3

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