# 4. digit_sum

#1

Can some one explain how I can build on this code I am getting a sum of 0

``````def digit_sum(n):
x=0
y=n/(10**x)
a=[]
while y >= 0.1:
a.append(n%(10**x))
break
x+=1
return sum(a)``````

#2

#### Let say you give the number 20 to the function, so n is 20. I put comments in the code.

``````def digit_sum(n):
x=0
y=n/(10**x)
a=[]

# at this point the value of each veriable are:
# n = 20
# x = 0
# y = 20, which is the result from "20/(10**0)"
# a = []

while y >= 0.1:
# Here, the condition is satisfied, which is y that is 20 is bigger than 0.1

a.append(n%(10**x))
# Here, the result of computation inside bracket is 0,
# which is 20%(10**0), then you append 0 to list a.
# So, list a now contain 0.

break
# Because you put break here, the while loop will stop.
# So the code bellow which is x+=1 is never executed because it is part of while-loop.
# so x is still zero.
x+=1

# Next, because the loop already stop, the next line that will be executed is "return sum(a)"
# Remember the list a is only contain 0 inside.
# So, when the function return sum(a), the result will be 0.
return sum(a)``````

Hope this help a bit.

#3

Thank you very much but my code seems to still show error even after I removed the break. if there is no break wouldn't 'a' be [0,0,2] and the sum 2? I really appreciate in you trying to help
def digit_sum(n):
n=abs(n)
x=0
a=10**x
b= x/a
digit_list=[]
while b >= 0.1:
digit= n%a
digit_list.append(digit)
x+=1
return sum(digit_list)

#4

You are welcome.
If you just remove the break, without changing the logic, I think it will go to infinite loop since the condition always satisfied. You can try to understand it by evaluating the result of each line of the code

Anyway, this is one way of doing the task.

1. Change n to string.
2. Since now n is a string, you can iterate it. So,
3. Take each character from the string and change it to integer.
4. Then use append to fill the character to num_list.
5. Then you can return sum(num_list)

#5

def digit_sum(n):
sum=0
while n!=0:
i=n%10
sum=i+sum
n=n//10
else:
return sum
print digit_sum(1234)

#6

x = raw_input("enter value to check total of digits")
def digit_sum(j):
sum=0
i= str(j)
for k in i:
k= int (k)
sum=sum+k
return sum
print digit_sum(x)

#7

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