# 4. digit_sum

#1

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?

Thanks!

``````n=input("enter a number")
n_str=str(n)

def digit_sum(n):
total=0
for x in range(0,len(str(n))):
num_str=n_str[x]
#print(num_str)
total=total+int(num_str)

print(digit_sum(n))``````

#2

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``````

#3

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):
talley.append(x)
if len(talley) ==len(n):
for y in talley:
total+=int(y)
print total

print digit_sum(434)

#4

The code you just posted will not run at all.

#5

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

#6

#7

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)

digit_sum(n)

#8

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

digit_sum(123)

#9

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