In this python tutorial, you will learn how to Check Whether a Number is Palindrome or Not using the if and else statements along with certain operators of the python programming language.
How to Check Whether a Number is Palindrome or Not?
Let’s take a look at the source code , here the values are given as input by the user in the code, the while loop along with certain operators carry out the function.
CASE 1:
RUN CODE SNIPPETCASE 2:
RUN CODE SNIPPET# Python Program to Check Whether a Number is Palindrome or Not num = input("Enter a number:") if num == num[::-1]: print("\nYes, its a palindrome") else: print("\nNo, its not a palindrome")
CASE 1:
INPUT:
1221
OUTPUT:
Enter a number: Yes, its a palindrome
CASE 2:
INPUT:
427
OUTPUT:
Enter a number: No, its not a palindrome
- Here we give the user the option to enter the values and the input values are scanned using the
input
function and are stored in the variablenum
with the statements/strings("Enter a number:")
. - In the STDIN section of the code editor the input values are entered.
- We declare an
if
statement followed by a:
with the conditionnum == num[::-1]
where if the condition is satisfied, theprint
function will display the statement("\nYes, its a palindrome")
. - If the condition is not satisfied, it will move on to the
else
statement where theprint
function will display the statement("\nNo, its not a palindrome")
. - In the above code, the function
num[::-1]
corresponds tostart:stop:step
, when we use[::-1]
it starts from the end towards the first taking each element, so it reverses the input value and will display reversed value, with the==
we check if the condition is true and the respectiveprint
statements are displayed.
NOTE:
- The if and else statements evaluates whether an expression is true or false. If a condition is true, the “if” statement is executed otherwise, the “else” statement is executed.
- The Comparison operator == determines if the values of two objects are equal.
- The colon : at the end of the if and else statement tells Python that the next line of code should only be run if the condition is true.
- The statement for the input function are enclosed in single quotes and parenthesis.
- The \n in the code indicates a new line or the end of a statement line or a string.
- The print statement/string to be displayed in enclosed in double quotes.
- The input() function allows a user to insert a value into a program, it returns a integer value.
- The statement for the input function are enclosed in single quotes and parenthesis.