-1
def palindrome_checker(a):
    if type(a) == "str":
        list1 = list(a.split(" "))
    elif type(a) == "int":
        stringified_a = str(a)
        list1 = list(stringified_a)
    else:
        list1 = a     
    list2 = list1[::-1]
    if list1 == list2:
            print("It's a palindrome")
    else:
            print("It's not a palindrome")

This is an unnecessarily complicated palindrome checking script that covers different user inputs. However, if presented with an int 1234 - it omits the "elif type = int" and "jumps" to else statement, assigns list1 with an int, and the program returns an error, since it's applying indexing to an int.

I tried debugging via "prints" at different stages, and i see that my script detects 1234 as an 'int' but still decides to jump to else, without stringifying the integer.

I'm new to python, and i feel like i'm missing something very obvious here and i'm low key embarrassed but i can't see whats wrong at all...

valg
  • 11
  • 2
  • 2
    you are comparing type against str (the type name), that's never true, i;e; `int` is never `'int'` – buran Oct 14 '22 at 11:58
  • Verify your assumptions: start your interpreter, enter `type("") == "str"` and `type(1) == "int"`, observe that the result is `False` in both cases. Then enter `type("")` and `type(1)` and see that they are not strings. – molbdnilo Oct 14 '22 at 12:10
  • Also note that `list("a ba".split(" "))` is `["a", "ba"]`, not `["a", "b", "a"]`. – molbdnilo Oct 14 '22 at 12:14

3 Answers3

0

Just use isinstance(a, str) instead of type(a) == "str" and likewise to check for integer.

0

That's because type() is not what you need! As documented in this post, it is not a valid and flexible option!

So, try using isinstance(a, int), like so:

def palindrome_checker(a):
    if isinstance(a, str):
        list1 = list(a.split(" "))
    elif isinstance(a, int):
        stringified_a = str(a)
        list1 = list(stringified_a)
    else:
        list1 = a
    list2 = list1[::-1]
    if list1 == list2:
        print("It's a palindrome")
    else:
        print("It's not a palindrome")


palindrome_checker(1234)
-1
def palindrome_checker(a):
a = str(a)

list1 = list(a)
list2 = list1[::-1]

if list1 == list2:
        print("It's a palindrome")
else:
        print("It's not a palindrome")