Https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/digitsum

I wanted to post this in python faq, but when I tried searching for it under the topics when creating this post it didn’t come up, and when I went to the python faq forum I couldn’t click on the topic button (it was greyed out). When I tried to reply to an already made post it had been locked my a moderator, so am having to create a new post in order to ask my question.

Anyway the question I have is related to the lesson: https://www.codecademy.com/courses/learn-python/lessons/practice-makes-perfect/exercises/digitsum.

The question I want to ask is why does it not accept an answer just by using the sum format? Like so:

def digit_sum(n):
 return sum(n)
print digit_sum([1,2,3,4])

As it still prints out 10 as the correct answer, it’s just the argument is entered as a list of arguments, rather then one argument, which then has to be turned into a string then concatenated together and then turned into an int, or the other way round. Even if the argument isn’t entered as a list when calling the function: print digit_sum(1234) an error is generated saying: int object is not iterable, I don’t know why this happens? Is it because python sees the argument as one object, and therefore cannot add it up, because it has nothing to add up?

The sum function is not what we’re expected to use. If I recall this exercise, we are handing in an integer. Integers cannot be iterated.

The idea of this exercise is that you are summing the digits of a single number. So if you had the number one hundred and twelve (112), it would sum the 3 digits to get 4. When you enter it as a list, you aren’t entering a single number, but a list of numbers, hence it is not meeting the goal of the lesson. That is also why sum doesn’t work, because you cannot sum a single digit.

Also just to add, but think of it from a user perspective (even if it seems silly). If you were to hand a user this function, what would be more intuitive to them: giving a single number of which the digits should be summed, or splitting that number into a list of digits first? Your way is technically a valid way of summing those digits, but it’s not a complete solution to the problem “sum the digits of a given number” since that number needs to be changed before input.

Broadly speaking, all the lessons in codecademy require you to do what they ask of you, even if there are other ways to get the same answer. The idea is that you actually see all the different ways of doing things, and work up to the correct way.

sum might return an answer that matches, but if you are being asked to add the numbers together yourself, then you have not passed the test requirements for that lesson until you do that.