-1

Write a program to see if the input number is a palindrome. If it is a palindrome, find the sum of digits of the number and print it. Else print (“Not a palindrome!”) My CODE:

num = int(input())
temp=num
rev=0
while num>0:
  dig=num%10
  rev=rev*10+dig
  num=num//10
if(temp==rev):
    print('It is a palindrome!')   
else:
  print('Not a palindrome!')

I have checked the condition for palindrome but how to sum the digits here to print only them as final result?

aaaaaa
  • 1
  • 1
  • 1
    Your palindrome check doesn't work for numbers that end with `0`. It will say that 1210 is a palindrome. – Barmar Apr 25 '22 at 15:37
  • How to correct it? – aaaaaa Apr 25 '22 at 15:38
  • Easiest way is to convert the number to a string and then check if that's a palindrome. – Barmar Apr 25 '22 at 15:39
  • @Barmar I think it won't say it's a palindrome, because 121 will not be equal to 1210 – Alexey S. Larionov Apr 25 '22 at 15:40
  • Sorry about that. – Barmar Apr 25 '22 at 15:40
  • Please help with sum of digits – aaaaaa Apr 25 '22 at 15:46
  • I know to sum digits separately but not after checking palindrome property – aaaaaa Apr 25 '22 at 15:47
  • Add `s = 0` at the start and `s += dig` inside your `while` loop. Then print `s` if the number is a palindrome. – Stuart Apr 25 '22 at 15:53
  • Not thinking about efficiency, you can simply add `print(f"Sum of digits: {sum(int(i) for i in repr(temp))}")` under the `if(temp==rev)`. This uses the built-in `sum` function. `int(i) for i in repr(temp)` is a generator expression that evaluates to a generator object that yields the digits in the number entered. `repr(temp)` converts the integer that `temp` refers to to a string (e.g. if `temp` is `767` then `repr(temp)` will return `"767"`). `int(i)` converts characters of the string (i.e. digits) referred to by `repr(temp)` to an integer. – OTheDev Apr 25 '22 at 16:33

1 Answers1

0

I'd simply convert the integer to string:

num = int(input('Input an integer\n'))

snum = str(num)

digit_sum = 0
if snum == snum[::-1]:
    print('%d is a palindrome' %num)
    for letter in snum:
        digit_sum += int(letter)
    print('The sum of the digits is %d' %digit_sum)
else:
    print('%d is no palindrome' %num)