Python Practice › Basic Programs › Program 26

Check a palindrome number

EasyBasic Programs · 26 of 40

Write a Python program to check whether a number is a palindrome (reads the same backwards, like 12321).

Advertisement
Input
12321, 12345
Output
12321 is a palindrome
12345 is not a palindrome

Approach

  1. Reverse the digits and compare with the original.

Solution

Python
def is_palindrome(n):    text = str(n)    return text == text[::-1] for n in [12321, 12345]:    print(n, "is a palindrome" if is_palindrome(n) else "is not a palindrome")
Output
12321 is a palindrome
12345 is not a palindrome

Line by line

Lines 2-3

Comparing the string with its reverse gives True or False directly.

Line 6

A conditional expression chooses the message.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs