# Stuck on digit_sum

#1

Hi, I'm stuck on the digit_sum exercise in Practice Makes Perfect. I tried to follow the hint by attempting to convert the input number into a string, split the string into a list, convert each element in the list into an integer, and then sum all the integers in the list. This is the code I came up with:

``````  def digit_sum(n):
if n > 0:
string = str(n)
n_list = string.split()
n_sum = sum(map(int, n_list))
return n_sum``````

It's not working but I can't for the life of me figure out why. I'm getting the error message 'Your function fails on digit_sum(434). It returns 434 when it should return 11', but I don't know why it's returning the original number. Any help would be very much appreciated, I'm fairly new to coding so I apologise if this is an obvious question.

#2

There are no spaces between the digits in string. That means string.split() will return [string], without the digits beeing seperated.

#3

I tried changing the code to include:

n_list = string.split(' ')

but I'm still getting the same error message. How do I add spaces between the strings?

#4

just convert your n in str and after iterate over it convert again to int

def digit_sum(n):
total = 0
n = str(n)
for i in n:
total = total + int(i)

#5

I realised that I misunderstood what eveat had said, and that the split function was just returning the whole number. I converted the string to a list instead and it works.

def digit_sum(n):
if n > 0:
string = str(n)
numbers = list(string)
n_sum = sum(map(int, numbers))
return n_sum

#6

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