# 4. digit_sum

#1

Why is my code not working? It prints correctly. I don't understand what the instructions are asking us to do. They are really vague.

``````def digit_sum(n):
total = 0
for x in range(4):
n = int(raw_input("Enter numbers to add: "))
total += n

print digit_sum(10)``````

#2

The instructions are fine. You need to take one number and sum the digits.

If you have the number 74315 the result must be 20. Because the digits sum is 7 + 4 + 3 + 1 + 5.

In your case digit_sum(74315) will not return the number 20. Instead of this the function will ask the user to enter some numbers and will return their sum. You don't need raw_input at all. Also you never use the given number.

#3

@jaydacoder The instructions is telling you to make a function where it takes a number, say '45' and add the digits, so it will become '9' (as the digits were 4 and 5, and their sum 9). You are restricting the number value in the for loop and making the code so it returns the number itself. I assume this was from you not understanding the directions, so you should be able to fix it now. If not, let me know.

Good luck!

#4

Thanks, got it to work now that i understand what the question is asking:

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

print digit_sum(-434)``````

#5

#6

A bunch of ways to solve this... I'm sure there are many more ways...

``````def digit_sum(n): #example 1
total=0
while n > 0:
total += n%10 + digit_sum(n//10)
else:
return 0

print digit_sum(1239)

def digit_sum(n): #example 2
total=0
if n > 0:
total += n%10 + digit_sum(n//10)
return float(total)
else:
return 0

print digit_sum(1238)

def digit_sum(n): #example 3
total=0
if n != 0:
total += n%10 + digit_sum(n//10)
else:
return 0

print digit_sum(1237)

def digit_sum(n): #example 4
a = abs(n)
b = str(a)
total=0
for i in b:
total += float(i)
It would also make sense that you make sure that `n` is of the data type that you need (string/number) and the while in the first one is just not necessary. Why would one use a loop to run only once.