Python Code Example: Palindrome number

A palindrome is a word that has the same meaning when read backwards as when read from the front. Examples of palindromes are: Anna, madam, level, racecar and many more.
Mathematics also knows palindromes. Here we talk about palindromes if the numbers do not change when the sequence of numbers is reversed, for example 22 or 141.

Check Palindrome number

This code checks if a given number is a palindrome or not. A palindrome number is a number that remains the same when its digits are reversed. For example, 121 is a palindrome number because it remains the same after its digits are reversed.

Here’s how the code works:

  1. The input number is stored in the x variable.
  2. A new variable rev is created to store the reverse of x.
  3. The code enters a while loop that continues until x is greater than 0.
  4. In each iteration of the loop: a. The last digit of x is obtained using the modulo operator (%). b. The value of rev is updated by adding the last digit to rev multiplied by 10. c. The value of x is updated by dividing x by 10 using integer division (//).
  5. After the loop is finished, the code checks if temp (the original input number) is equal to rev (the reverse of the input number).
  6. If temp and rev are equal, the code prints a message indicating that the input number is a palindrome number.
  7. If temp and rev are not equal, the code prints a message indicating that the input number is not a palindrome number.
rev = 0
x = int(input("Enter number to check palindrome or not: "))
temp = x


while x > 0:
    r = x % 10
    rev = rev * 10 + r
    x = x // 10

if temp == rev:
    print(str(temp) + " is palindrome number")
else:
    print(str(temp) + " is not palindrome number")
Output
Enter number to check palindrome or not: 262
262 is palindrome number

Enter number to check palindrome or not: 13
13 is not palindrome number

Check Palindrome string

The code checks if a given string s is a palindrome or not. A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward.

The code starts by initializing a string s to “anna”. Then, an if statement is used to check if s is equal to its reverse, which is obtained by slicing s in reverse using the step parameter [::-1]. If s is equal to its reverse, the code prints s + " is a palindrome". If not, the code prints s + " is not a palindrome".

In this case, the code will print “anna is a palindrome”, as the string “anna” is a palindrome.

s = "anna"
 
if s == s[::-1]:
    print(s + " is a palindrome")
else:
    print(s + " is not a palindrome")
Output
anna is a palindrome