Digit Sum


#1

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

digit_sum(432432)

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

V/R


#2

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

here:

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)


#3

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


#4

positive integers means greater then zero, not even number

so you can get rid of that if condition


#5

A post was split to a new topic: Digit sum


#6

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