#1

I didn't know how to solve this problem, so searched, and this is the one I'm trying to understand.
I thought it would be nice to share. There are one way we can do based on what we learned at the codecademy, but another using 'map.'

You have to change it to a string first :

``````In [24]: num = 123456

In [25]: sum(int(x) for x in str(num))
Out[25]: 21``````

Without converting to a string:

``````def solve(n):
summ=0
while n:
summ+= n%10
n/=10
return summ

....:

In [38]: solve(123456)
Out[38]: 21``````

``````In [1]: num=123456

In [2]: sum(map(int,str(num)))
Out[2]: 21

In [3]: def digitsum(x):
...:     return sum(map(int,str(x)))
...:

In [4]: digitsum(num)
Out[4]: 21``````

#2

I am sorry. None of the two brings the right result in codecademy.
Maybe somebody can explain why?

Thank you!

#3

Go here for my solution to the problem

#4

@medouxa

Hi friends,

After quite a bit of try and error and searching, I found a relatively simple and understandable way to solve this:

``````def digit_sum(n):
num= sum(map(int, str(n)))
return num``````

Going through the Python docs makes the applied syntax clearer.

Cheers

#5

code for the challenge!
def digit_sum(n):
countn=0
while n!=0:
countn += n%10
n=int(n/10)
return countn

#6

That worked for me:

``````def digit_sum(n):
count = 0
suma = 0
n = str(n)
z = len(n)
print z
while count < z:
x = n[count]
x = int(x)
suma += x
count += 1
else:
print count
print suma
return suma
return count
digit_sum(434)``````

#7
``````import math
def digit_sum(n):
nstr=str(n)
print nstr
summation=0
for i in nstr:
summation+=int(i)

return summation``````

#8

can somebody please let me know, what is wrong with the below code:
def digit_sum(n):
num_sum = 0
digits = len(str(abs(n)))
digits = int(digits)
while digits != 0:
last_num = n%10
num_sum = num_sum + last_num
digits -= digits
n = n // 10
return num_sum