How to check if a number is a palindrome in Python
How to check if a number is a palindrome in Python.
Here's a step-by-step tutorial on how to check if a number is a palindrome in Python:
Step 1: Start by defining a function named is_palindrome
that takes a single parameter num
, which represents the number we want to check.
Step 2: Convert the number to a string using the str()
function. This will allow us to easily access individual digits.
Step 3: Check if the string representation of the number is equal to its reverse. If they are equal, then the number is a palindrome. You can use string slicing with a step of -1 to reverse the string.
Here's the code for the is_palindrome
function:
def is_palindrome(num):
num_str = str(num)
reversed_str = num_str[::-1]
if num_str == reversed_str:
return True
else:
return False
Now, you can call the is_palindrome
function and pass in the number you want to check. It will return True
if the number is a palindrome and False
otherwise.
Here are a few examples of how you can use the is_palindrome
function:
print(is_palindrome(12321)) # Output: True
print(is_palindrome(12345)) # Output: False
print(is_palindrome(1221)) # Output: True
print(is_palindrome(987789)) # Output: True
In the first example, the number 12321 is a palindrome, so the function returns True
. In the second example, the number 12345 is not a palindrome, so the function returns False
. The third and fourth examples are also palindromes, so the function returns True
for both.
That's it! You now have a working function to check if a number is a palindrome in Python.