Palindrome program in python

A number or string is said to be a palindrome if we invert the number or string and the string or number remains the same as the original number or string.

Example:

Rule to check palindrome:

  • Read the given input and hold it in the temporary variable.
  • Reverse the input.
  • Compare temporary variable with reversed input.
  • If both are the same, the input string or number is a palindrome.
  • Else input string or number is not a palindrome.
  • End the program.

Example 1:

The following is a basic source code to check the palindrome:

Output

Here is the result:

Palindrome program in Python

Explanation: In this program, we have taken a string and store it into a variable string1. The method casefold() makes it suitable for caseless comparisons and returns the string in lowercase. The reversed() function will reverse the original string. Since this function returns a reversed object, we use the list() function to convert them into a list before comparing. Finally, we will compare this string with the original string using the IF statement. If both strings are the same, it will print the string as a palindrome. Else it prints string is not a Palindrome.

Example 2: Palindrome string program using inbuilt function

Here is the source code:

Output

CASE 1:

Palindrome program in Python

CASE 2:

Palindrome program in Python

Explanation: The extended slice operator will reverse the string and then compare it with the original string using the IF statement. If both string matches, the string is a palindrome. Else the string is not a palindrome.

Example 3: Palindrome Program using While Loop

The source code is given below:

Output

CASE 1:

Palindrome program in Python

CASE 2:

Palindrome program in Python

Explanation: In this program, a user will be asked to enter a number to check if the number is palindrome or not. This number will store in a variable named number. A temporary variable temp is used to hold the value of the number during the execution of the program, and another variable, reverse, is also declared and initialized as value 0.

We will obtain each digit of the given number by using the modulus operator %. The reverse value will be calculated using reverse * 10 + digit and get updated. This process will continue till the value of the number become zero.

Now, if(temp == reverse) condition checks whether the input number is exactly equal to the reverse number or not. If this condition is true, then it is a Palindrome. Else the given number is not a Palindrome number.

Pin It on Pinterest

Share This