# 15/4 def digit_sum Q

#1

I want to write a Code which automatically adds all digits for the length of the number in question.
But for that to happen i would need to have an operation which automatically creates indexes, till it reaches the numberes length. And i cant get that done. May you please help me?

In the first part of my Code you find the manual way i want to automate.
When it starts the second time (def digit_sum(n)...) thatÂ´s what i am talking about.

``````def digit_sum(n):
string=str(n)
lngth=len(string)
intgr=int(n)
result=0
n1=string[0]
n2=string[1]
n3=string[2]
n4=string[3]
result=int(n1)+int(n2)+int(n3)+int(n4)
print result

digit_sum(1234)

def digit_sum(n):
string=str(n)
lngth=len(string)
intgr=int(n)
result=0
index1=0
index2=0
for x in range(lngth):
n1=string[index1]

digit_sum(1234)``````

#2

We will want our program to handle any size number so need a dynamic environment, not a static one. How do we know how many indices we need before hand? Suggest take this back to the drawing board and begin again with a more dynamic approach.

``s = str(n)``

Now `s` has an index `in range(0, len(s))` which we can iterate over and accumulate a total.

``````total = 0
for i in range(len(s)):
total += int(s[i])

or,

``````total = 0
for x in s:
total += int(x)
``````def digit_sum(n):