 # 4/15 digit_sum

Hello all,

Can someone explain to me why my code is doing this and how to fix it?

``````def digit_sum(n):
digit_string = str(n)
for i in digit_string:
digit_list.append(i)
int_list = map(int, digit_list)
sum_list = sum(int_list)
print sum_list

digit_sum(454)

``````

Output is this
4
9
13
None

Error is: Oops, try again. Your function fails on digit_sum(434). It returns None when it should return 11.

I am not sure how to get the last list, the one with all of the numbers in the list, instead of the numbers being put in individually and that list being displayed. To clarify, how can create just one list instead of multiple lists?

Well, you are creating only one list (`digit_list`), but you print the result after every digit. Why? Because your `print` statement is in the body of the `for` loop.

``````def digit_sum(n):
digit_list = []
digit_string = str(n)
for i in digit_string:
digit_list.append(i)
int_list = map(int, digit_list)
sum_list = sum(int_list)
print sum_list

digit_sum(454)
``````

This code is not correct yet. According to the error message your function should `return` the result, not `print` it out to the console.

2 Likes

Thanks so much for your input!

My new code works great!

``````
def digit_sum(n): #define our funtion
digit_list = [] #create a new empty list
digit_string = str(n) #convert digits to strings
for i in digit_string: #runs through the numbers in list of                                   strings
digit_list.append(i) #adds the numbers(strings) to the new                                list
int_list = map(int, digit_list) #converts every string to an                                          integer from the digit_list
sum_list = sum(int_list) #adds all of the values from the list
return sum_list    #returns the final list with our answer
print digit_sum(1500)

``````
3 Likes

Just sharing the code I wrote on top of my head for this exrecise, didn’t optimize it to be short, to say the least. It works fine in the actual python interpreter but fails to pass the exercise .
I didn’t use str conversion :).

Cheers.

`import time

def digit_sum(x):
numbers =
original_number = x
while x > 0:
tmp = x % 10
numbers.append(tmp)
print “Added ‘{0}’ to the list”.format(tmp)
x = x // 10
print “So far we have the following numbers: ‘{0}’”.format(numbers)
print “Calculating…\n…”
time.sleep(5)
print “the sum of all the digits in your number (’{0}’) is: ‘{1}’”.format(original_number, sum(numbers))

digit_sum(2823)
`

You’re very welcome Your code looks great, but you can optimize it a bit. Please note that these two operations:

``````int_list = map(int, digit_list) #converts every string to an integer from the digit_list
sum_list = sum(int_list) #adds all of the values from the list
``````

are inside the `for` loop. This means that they are executed after addition of every digit. Is this necessary? Not really. You can execute them only once, after the `for` loop Is line 5 the reason why this is failing with two numbers? It works if I set n individually…

1. num=
2. def digit_sum(n):
3. ``````total = 0
``````
4. ``````for i in range(0,len(str(n))):
``````
5. ``````    total += (n//10**i)%10
``````
6. ``````else:
``````
7. ``````    num.append(total)
``````
8. ``````    print num
``````

The problem is that variable `num` is defined globally. After first execution of your function this variable has some value and that is why second function call will return incorrect result. You should move definition of this object to the scope of `digit_sum` function.

And you should print the result as integer, not as a list.

I would suggest you to try to answer this question - do you really need `num` variable? I mean, whole digit sum is stored inside the `total` variable, right? 1 Like

Hi, would you like to review my code below? it gives the right result, but if i compare to your codes above, mine was really different. Do you see any weaknesses of this code:

``````def digit_sum(n):
nlist = []
n = str(n)
for number in n:
nlist.append(number)
new_list = [int(number) for number in nlist]
now = sum(new_list)
return now
``````

many thanks before 2 Likes

Looks good to me… (i am using it since I can’t get over mine) def digit_sum(n):
total = 0
print n
for i in range(0,len(str(n))):
total += (n//10**i)%10
else:
print total

digit_sum(n)
434
11

Your code is correct, but it can be easily improved Please note that string is already a list of the characters. That is why `nList` and the first `for` loop is not needed.

``````def digit_sum(n):
n = str(n)
new_list = [int(number) for number in n]
now = sum(new_list)
return now
``````

And now is the question - do we really need all these variables? Nope. Remember that if you use a variable only in one place - you don’t need it. Let’s make this code more pythonic ``````def digit_sum(n):
return sum([int(number) for number in str(n)])``````
11 Likes

I see,

That’s really simpler than i thought!

Thank you yaa!! You’re very welcome I got how it works with a list, however when I tried without a list, and a variable “total” instead, it doesn’t work and I can’t figure out why

``````def digit_sum(n):
string_n = str(n)
for x in string_n:
total = 0
int(x) += total
``````
``total = total + int(x)``

Doing the other way around doesn’t work in Python.

thank you there, it is fixed also I realized total = 0 need to be outside the loop

1 Like

No problem, Benjamin! Glad to help!

This is nearly the same as what I did:

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

Here is my code. It works well. Hope it helps. 1 Like

Hope it helps:

``````  def digit_sum(n):
total = 0
while (n//10)!=0:
total += (n%10)
n=n//10
total +=n
``````def digit_sum(n):