4. digit_sum


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/4?curriculum_id=4f89dab3d788890003000096

Hi everyone, could you help solve my problem?
I think my idea is right, but it dose not work.


def digit_sum(n):
    i=0
    sum=0
    while (n>=10):
        n/=10.0
        i+=1
    for item in range(i+1):
        sum+=int(n)
        n=(n-int(n))*10.0
    return sum


#3

Should you really be using two loops? If you do it manually, to you read each digit twice? Or is it enough with one pass? And if once is enough, then what does the other loop do? What exactly should be done for each digit? Is either loop doing that something?


#4

n= raw_input ("chose a number with four digits :")

def digit_sum(n):
x = str(n) #change to string
num = 0
for digit in x:
num=num + int(digit) #change to integer
return num
print digit_sum(55)


#5

I understand your way is more simple.
And I also know my way is inefficient, but could you help me figure out why it does not work?