Search code examples
sumsum-of-digits

Calculate the sum of the digits using python


I would like to find the sum of the digits using python. when i enter a birth year 1982 the result should be 1+9+8+2 = 20 final total result is 2+0 = 2.

The reason that i am posting this question is i didn't find any simple python solution for this.

This is my code

num = int(input("Enter your birth year: "))
x  = num //1000
x1 = (num - x*1000)//100
x2 = (num - x*1000 - x1*100)//10
x3 = num - x*1000 - x1*100 - x2*10
x4 = x+x1+x2+x3
num2 = int(x4)
x6 = num2 //10
x7 = (num2 -x6)//10

print("your birth number is" ,x6+x7)

but i am not getting the correct sum value.


Solution

  • Try adding some debug statements to inspect values as your program runs.

    num = int(input("Enter your birth year: "))
    x  = num //1000
    x1 = (num - x*1000)//100
    x2 = (num - x*1000 - x1*100)//10
    x3 = num - x*1000 - x1*100 - x2*10
    print (x, x1, x2, x3)
    x4 = x+x1+x2+x3
    print (x4)
    num2 = int(x4)
    x6 = num2 //10
    x7 = (num2 -x6)//10
    print (x6, x7)
    print("your birth number is" ,x6+x7)
    

    You'll quickly find your problem.