Palindrome Python Program:
This code is a Python program that checks whether an input integer is a palindrome or not.
Code:
# Read the input
num=int(input("Enter a number:"))
#Store it in temp variable
temp=num
rev=0
#Reversing the integer
while(num>0):
dig=num%10
rev=rev*10+dig
num=num//10
#Checking if it is a palindrome or not
if(temp==rev):
print("The number is palindrome!")
else:
print("Not a palindrome!")
Output:
Enter a number:121
The number is palindrome!
Explanation:
- num=int(input("Enter a number:")): This line prompts the user to enter a number, converts the input to an integer using the int() function, and assigns it to the variable num.
- temp=num: This line creates a variable temp and assigns the value of num to it. This is done to preserve the original value of num, which will be used later to check if the number is a palindrome.
- rev=0: This line initializes the variable rev to 0, which will be used to store the reverse of the number.
- while(num>0):: This line starts a while loop that runs until num becomes 0.
- dig=num%10: This line calculates the last digit of num using the modulo operator % and assigns it to the variable dig.
- rev=rev*10+dig: This line appends the digit dig to the rev variable, which is being constructed in reverse.
- num=num//10: This line removes the last digit of num using the integer division operator //. This is done in each iteration of the loop, to obtain the remaining digits of the number.
- if(temp==rev):: This line checks if the original number temp is equal to its reverse rev.
- print("The number is palindrome!"): This line is executed if the number is a palindrome, i.e., if temp is equal to rev.
- else: print("Not a palindrome!"): This line is executed if the number is not a palindrome.