4. digit_sum



Hi All,
I get the error message:
-Your function crashed on 1000 as input because your function throws a "string index out of range" error.
-Your function fails on digit_sum(434). It returns 1 when it should return 11

Can someone show me where my code is going wrong?


n=input("enter a number")

def digit_sum(n):
	for x in range(0,len(str(n))):
	print("Your total is: %s"%(total))
	return total


Your function should base its result only on the argument that is given to it.

However, it is also making use of a global variable which essentially refers to junk data (and you shouldn't be reading junk)

Additionally, you should not use input because it evaluates the input (in other words gives control of the program to the person who you're allowing to type in arbitrary code there)
Use raw_input instead to read a string.

It's also probably easier to hard-code test data than to type it in every time that you run the code, for example by adding the following at the end of the code:

assert digit_sum(434) == 11
assert digit_sum(1000) == 1


Why does my code print out "None" after it completes summation? Thanks in advance.

def digit_sum(n):
#convert number to string for iteration
talley =[]
n = str(n)
total = 0
#iterate through the list splitting up the 'word'
for x in str(n):
if len(talley) ==len(n):
for y in talley:
print total

print digit_sum(434)


The code you just posted will not run at all.


As you can see it does run. Thanks for the response. Hopefully someone else can offer some guidance.


the problem asks you to return total, not print total


Shorter way. maybe.

n = raw_input("Enter a number: ")

def digit_sum(n):
number = [(int(item)) for item in str(n)]
#print number
#print sum(number)
return sum(number)



def digit_sum(n):
sum = 0
n = str(n)
for digit in n:
digit = int(digit)
sum = sum + digit
print sum
return sum



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