String index out of context error


#1

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

Error : Oops, try again. Your code looks a bit off--it threw a "string index out of range" error

why isnt the code working ?


x = 0
y = 0
z = 0
u = 0

a = 0
b = 0
c = 0

new_one = 0
new_two = 0
new_three = 0

def digit_sum(n):
    y = n // 1000  
        
    z = n // 100
    z = str(z)
    for a in z:
        new_one = a[1]
        new_one = int(new_one)
        
    x = n // 10
    x = str(x)
    for b in x:
        new_two = b[2]
        new_two = int(new_two)
    
    u = n // 1
    u = str(u)
    for c in u:
        new_three = c[3]
        new_three = int(new_three)

    return y + new_one + new_two + new_three


#2

@arraymaster34421
Do it bit by bit with a lot of print's
so you get an idear of what you are doing....

def digit_sum(n):
    y = n // 1000  
    print("y: {0} is {1}".format(y,type(y)))
    z = n // 100
    print("z: {0} is {1}".format(z,type(z)))
    z = str(z)
    print("z: {0} is {1}".format(z,type(z)))
    for a in z:
        print("a: {0} is {1}".format(a,type(a)))
        new_one = a
        new_one = int(new_one)
    print("new_one: {0} is {1}".format(new_one,type(new_one)))
digit_sum(12345)

#3

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