Member-only story
Python Program to Check if a Number is a Palindrome
1 min readNov 26, 2024
num = input("Enter a number: ")
if num == num[::-1]:
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")
1. num = input("Enter a number: ")
- Purpose: Prompts the user to input a number.
- Result: Stores the user’s input as a string in the variable
num
. - Example: If the user enters
121
, thennum
is"121"
(a string, not an integer).
2. if num == num[::-1]:
- Purpose: Compares the string
num
with its reverse (num[::-1]
). num[::-1]
: This uses Python slicing to reverse the string.
Syntax:
[::-1]
: Start from the end of the string and move backward (reverse the order).
Example:
- If
num = "121"
, thennum[::-1] = "121"
. - If
num = "123"
, thennum[::-1] = "321"
.
Comparison:
- If
num
is the same asnum[::-1]
, the input is a palindrome. - Otherwise, it is not a palindrome.
3. print(f"{num} is a palindrome.")
- If the condition
num == num[::-1]
is True, this statement is executed.
Example:
- Input:
"121"
- Output:
121 is a palindrome.
4. else: print(f"{num} is not a palindrome.")
- If the condition
num == num[::-1]
is False, this statement runs.
Example:
- Input:
"123"
- Output:
123 is not a palindrome.