-2

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.

Arun Oid
  • 11
  • 6

2 Answers2

0

Sum the digits of an integer until the result is a one-digit integer:

def sum_digits(num):
    num = str(num)
    if len(num) < 2:
        return int(num)
    else:
        return sum_digits(sum([int(dig) for dig in str(num)]))

>> sum_digits(1982)
2

Or a simpler version for the case your number is a year:

def sum_digits(num):
    return sum([int(dig) for dig in str(num)])

Just call the function twice

>> sum_digits(sum_digits(1982))
2
Andreas K.
  • 9,282
  • 3
  • 40
  • 45
  • Very interesting that the other three answers on this question are all downvoted! – Kirk Broadhurst Mar 01 '18 at 22:32
  • What are you implying? I didn't downvote the question or the answers. – Andreas K. Mar 01 '18 at 22:39
  • If i remove this question completely my stackoverflow REPUTATION will be 8. But its seems this questions is somehow interesting so i am going to keep this for while in here until someone up vote. – Arun Oid Mar 06 '18 at 19:02
-1

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.

Kirk Broadhurst
  • 27,836
  • 16
  • 104
  • 169