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 : num = 123456 In : sum(int(x) for x in str(num)) Out: 21
Without converting to a string:
def solve(n): summ=0 while n: summ+= n%10 n/=10 return summ ....: In : solve(123456) Out: 21
In : num=123456 In : sum(map(int,str(num))) Out: 21 In : def digitsum(x): ...: return sum(map(int,str(x))) ...: In : digitsum(num) Out: 21