Digit Sum


Hi, I need help with my code.

Instructions: Write a function called digit_sum that takes a positive integer n as input and returns the sum of all that number’s digits. For example: digit_sum(1234) should return 10 which is 1 + 2 + 3 + 4. (Assume that the number you are given will always be positive.)

My code:

def digit_sum(n):
if n % 2 == 0:
total = 0
for i in (n):
total = total + n(i)
return total


I understand the concept of indexing, I just to make sure if my code is correct.



why if n % 2 == 0? I don’t see the point

n is integers, so it can’t be looped over:

for i in (n):

this would require an iterable, like a string, we can cast integers to string


total = total + n(i)

once you converted n to string, i will be values from the list, why would you attempt to use i as index for n list? Besides, even if you wanted to (you don’t) accessing by index is done using square brackets, not parentheses, this will make it a function call (something you most certainly do not want)


Thank you. I thought I had to put n%2 == 0, because it has to be a even number?


positive integers means greater then zero, not even number

so you can get rid of that if condition


A post was split to a new topic: Digit sum


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