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.
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:
x
variable.rev
is created to store the reverse of x
.x
is greater than 0.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 (//
).temp
(the original input number) is equal to rev
(the reverse of the input number).temp
and rev
are equal, the code prints a message indicating that the input number is a palindrome number.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")
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
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")
anna is a palindrome