Help with code without using string method


#1



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

The code runs without errors but it always fails to add the last digit. This is what I htink my code should do


n=12
x=1
l=[ ]
12/10=1.2>0.1
y=2 # 12%10 = 2
y=int(2/1)=2 (2/1)
l=[2]

x=2
l=[2]
12/100=.12>0.1
y=12
y=int(12/10)=1
l=[0,2,1]

I had similar issue with the last digit missing in sum for other numbers


def digit_sum(n):
    n = abs(n)
    x = 1
    l = []
    while n/(10**x) >= 0.1:
        y = n%(10**x)
        l.append(int(y/(10**(x-1))));
        x += 1
    print sum(l)
    
print digit_sum(12)


#2

Sounds like your loop is off by one, doesn't it? So you'd need to find out if it's the first or last and then reconsider the start value or condition


#3

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