-1

I am currently struggling with a homework problem and I need some help, as I feel like I'm a bit confused. I work on creating a program that looks for palindromes within integers only. The program I've made I know will accurately identify palindromes within integers, but I cannot get the program to identify when the input is not an integer (float, bool, str, etc.). I specifically want the program to note when an integer is not the input and print "The input is not an integer" before breaking. Here is my code below:

def Palindrome(n):
     return n == n[::-1]

n = input("Please enter an integer: ")

ans = Palindrome(n)

if ans == True:
    print("The number " + n + " is a palindrome")
elif ans == False:
    print("The number " + n + " is NOT a palindrome")

I know this is kind of basic, but everyone needs to start somewhere! If anyone could explain what I could do to create the program and understand how it works, it would be very appreciated :)

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44

2 Answers2

0

Your palindrome() function has some indentation issues.

def palindrome(n):
    return n == n[::-1]

This function can basically check whether a string str is a palindrome, and not just limited to integers.

n = input("Please enter anything: ")

is_palindrome = palindrome(n)

if is_palindrome:
    print(n + " is a palindrome.")
else:
    print(n + " is not a palindrome.")

Output

Test case A for racecar.

Please enter anything: racecar
racecar is a palindrome.

Test case B for 123.

Please enter anything: 123
123 is not a palindrome.
Troll
  • 1,895
  • 3
  • 15
  • 34
0

When you get an input it's always a string value, so a possible solution is to modify Palindrome. First, try to cast the input to int and then print and exit if it throws a ValueException in this way.

def Palindrome(n):
    try:
        int(n)
    except ValueError as e:
        raise ValueError('The value must be an integer')
    return n == n[::-1]

if __name__ == "__main__":
    
    try:
        n = input("Please enter an integer: ")
        ans = Palindrome(n)

        if ans == True:
            print("The number " + n + " is a palindrome")

        elif ans == False:
            print("The number " + n + " is NOT a palindrome")
    
    except ValueError as e:
        print(str(e))
Federico A.
  • 256
  • 2
  • 8
  • 1
    Doing `sys.exit(0)` to signal an error from inside a function instead of raising a(nother) exception has to be one of the misdirected ideas. (Adding insult to injury, 0 is the exit code for success.) – tripleee Oct 20 '21 at 05:50
  • Omg, I totally agree with you. Thank you for the revision! I'm going to edit my post. – Federico A. Oct 23 '21 at 01:00