Search code examples
pythonsyntax-errorpalindromelogic-error

Palindrome number checking. I have the main concept working, not sure if my one MAIN error is fixable though


In this problem I am to accept a user input and then check to see if the number is a palindrome.

This is my code :

def ispal(number):
     mod = len(number) % 2 
     if (mod == 0): #if number entered is even number of digits long
          x = 0 #checks beginning
          y = len(number) 
          z = y / 2 #if number is 4 digits long i only want it to run twice because i have the program to iterate starting from the beginning and end of number
          while x <= z:
               if (number[x] == number[y-1]):
                    x+=1
                    y-=1
          return True
     elif (mod == 1):
          x = 0
          y = len(number)
          z = (y/2)-0.5
          while x <= z:
               if (number[x] == number[y-1]):
                    x+=1
                    y-=1
          return True
     else:
          return False

user = str(input("Enter a number and this program will tell you if it is a palindrome: "))
ans = ispal(user)
if (ans == True):
     print("is palindrome")
elif (ans == False):
     print("is not palindrome")

I realized now that because I didn't just reverse the number but instead used mod to check if the number was odd or even in length checking for false cases is tricky. Any clues? Is this method viable over reversing the number? Is this method vs reversing the number have merit in an actual applied scenario?


Solution

  • You need to return False when the check that the two digits are the same fails.

                while x <= z:
                    if (number[x] == number[y-1]):
                        x+=1
                        y-=1
                    else:
                        return False