Write a Python program to take a number and check if it’s a palindrome or not
Question
Now the trend has changed a bit, interviewer do not shy away from asking basic python programs.
12321
12345
Palindrome
Non-Palindrome
solved
0
Python
55 years
14 Answers
1064 views
Grand Master 0
Answers ( 14 )
We will ask the user to input a number and then reverse it and match it with the number provided by the user.
n = input(“Enter the number : “) -> Number
rev = n[::-1] -> Reversed the number
if rev==n : -> Comparing
print(“Palindrome”)
else:
print(“Non-Palindrome”)
numb = 12321
If numb == numb[::-1]:
Print(“Palindrome”)
Else:
Print(“not Palindrome”)
n=int(input(“Enter number:”))
temp=n
rev=0
while(n>0): dig=n%10
rev=rev*10+dig n=n//10
if(temp==rev): print(“The number is a palindrome!”)
else: print(“The number isn’t a palindrome!”)
We would define a function to determine if a number is a palindrome or not in the following manner:
def palindrome (number):
if str(number)==str(number)[::-1]:
print(‘Palindrome’)
else:
print(‘Not Palindrome’)
The function can be used as follows:
palindrome(12321)
output: Palindrome
palindrome(12345)
output: Not Palindrome
number = 12321
reverse_nu = str(number)[::-1]
if number == reverse_nu:
print(“Number is Palindrome”)
else:
print(“Number is not a Non Palindrome)
n=12321 #inputing a sample number
n=str(n) #changing it into a string
print(n[::-1]==n) #returns true if a palindrome
n[-1] returns the last element of the array. n[::-1] would return the reversed string
To go by the basic logic, I will use the basic commands to check whether the number is palindrome or not. The other short method is already given by a lot of people.
num=int(input(“Enter a number”))
rev=0
while(num>0):
digit=num%10
rev=rev*10+digit
num=num/10
if (num==rev):
print(“Palindrome”)
else:
print(“Non-palindrome”)
number = 12321
If number == number[::-1]:
Print(“Palindrome”)
Else:
Print(“not Palindrome”)
st=”12345″
s1=””
for i in st:
s1=s1+i
if s1==st:
print(“palindrome”)
else:
print(“not”)
num=int(input(“Enter a number”))
rev=0
while(num>0):
digit=num%10
rev=rev*10+digit
num=num/10
if (num==rev):
print(“Palindrome”)
else:
print(“Non-palindrome”)
#Basic approach iterate the input till half of the input length and compare first and last parts of inputs
def Pallindrome(n):
a = int(len(n))
for i in range(0,int((a)/2)):
if n[i]!=n[len(n)-i-1]:
return False
return True
n = input(‘enter text/string’)
chck = Pallindrome(n)
if (chck):
print(‘its a pallindrome’)
else:
print(‘not a pallindrome’)
user_string = ‘12321’
if user_string == user_string[::-1]:
print(‘it is palindrome’)
else:
print(‘it is not palindrome’)
user_strin = ‘12321’
if user_strin == user_strin[::-1]:
print(‘it is palindrome’)
else:
print(‘it is not palindrome’)
user = ‘12321’
if user == user[::-1]:
print(‘it is palindrome’)
else:
print(‘it is not palindrome’)