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


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_tot = list_tot + list[i]
    return list_tot

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

print digit_sum(numb_txt)


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:


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


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