what is palindrome in python

10 months ago 67
Nature

A palindrome is a sequence of characters, words, or numbers that reads the same backward as forward

. In Python, you can check if a given string or number is a palindrome using various methods. Here are two common methods:

  1. Using a while loop :
python

def is_palindrome(num):
    temp = num
    rev = 0
    while (num > 0):
        dig = num % 10
        rev = rev * 10 + dig
        num = num // 10
    if (temp == rev):
        return True
    else:
        return False

This function takes a number as input, reverses it using a while loop, and then compares the original number with the reversed number. If they are the same, the function returns True, indicating that the number is a palindrome

  1. Using built-in functions :
python

def is_palindrome(s):
    return s.lower() == s[::-1]

This function takes a string as input, converts it to lowercase, and then reverses it using slicing. It then checks if the original string is equal to the reversed string. If they are the same, the function returns True, indicating that the string is a palindrome

. Here are some examples of how to use these functions:

python

print(is_palindrome(121))  # Output: True
print(is_palindrome("malayalam"))  # Output: True
print(is_palindrome("geeks"))  # Output: False