Skip to main content
2 of 6
added 843 characters in body
syb0rg
  • 21.9k
  • 10
  • 113
  • 193

A few notes:

  • A more pythonic way to determine if a given value is a palindrome:

     str(n) == str(n)[::-1]
    

    You do something similar in your code, but are converting from a string back to an int. This is more readable to me.

  • Use the palindrome test as a check with the while loop:

     while str(n) != str(n)[::-1]:
    
  • In the while loop, use the logic you already have to add on a reversed int:

     n += int(str(n)[::-1])
    
  • I would make it easier to input a number for the code to use, I did this with argparse.

     def get_args():
         parser = argparse.ArgumentParser(description=
             'Generate palindrome from number when added to its reverse')
         parser.add_argument('num', type=int, help='number for palindrome generator')
         return parser.parse_args()
    

Final Code

import argparse

def get_args():
    parser = argparse.ArgumentParser(description=
        'Generate palindrome from number when added to its reverse')
    parser.add_argument('num', type=int, help='number for palindrome generator')
    return parser.parse_args()
    

def main():
    args = get_args()
    while str(args.num) != str(args.num)[::-1]:
        args.num += int(str(args.num)[::-1])
        
    print(args.num)

if __name__ == "__main__":
    main()

Test run:

$ python test.py 146
787
syb0rg
  • 21.9k
  • 10
  • 113
  • 193