Digit_Sum


#1


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

I am not sure why I can not return the sum(result)? I used print statements to check my work and the algorithm works with the print statement but the console won't accept return sum(result). Is there some limitation to the result function I'm not understanding?


result = []

def digit_sum(n):
    s = str(n)
    for char in s:
        result.append(int(char))
    #print result
    return sum(result)
    
digit_sum(1111)


#2

You cannot use integer methods like sum(). On a string,


#3

In this case you can use int() on a string because the string is a string of a number. The int() is a python built in function that converts a string of a number into an integer.

source: Converting Strings with int()

I figured out the problem was I had a global variable, result, that I did not declare using the global keyword in my function.


#4

Yes I know that but in your code you converted into a string just for iteration. Unnecessary. :slight_smile:


#5

He his using sum() on a list, which is legit. The problem is that the empty list is defined in global scope so never gets reset to empty on each call to the function.

Define result = [] inside the function, before the loop.

But valid. The code converts str to int as expected.


#7