Here’s an example Python function that checks if a number is a palindrome or not:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | def is_palindrome(num): """ Returns True if num is a palindrome, False otherwise """ # Convert the number to a string str_num = str(num) # Check if the string is the same forwards and backwards if str_num == str_num[::-1]: return True else: return False |
Here’s how you can use this function to check if a number is a palindrome:
1 2 3 4 5 6 7 | num = 12321 if is_palindrome(num): print(num, "is a palindrome") else: print(num, "is not a palindrome") |
This will output:
1 2 3 | 12321 is a palindrome |
Here’s a step-by-step explanation of how the is_palindrome
function works:
The function is_palindrome
takes a single argument num
, which is the number we want to check if it’s a palindrome.
We convert the number to a string using the str()
function, so that we can easily compare its characters forwards and backwards.
1 2 3 | str_num = str(num) |
For example, if num
is 12321
, str_num
will be the string "12321"
.
We check if the string is the same forwards and backwards using slicing. If the string is a palindrome, it will be the same forwards and backwards when we reverse the order of the characters. We can do this using the slice notation [::-1]
, which returns the string in reverse order.
1 2 3 4 5 6 | if str_num == str_num[::-1]: return True else: return False |
For example, if str_num
is "12321"
, then str_num[::-1]
will be "12321"
as well, since the characters are the same forwards and backwards. If str_num
is "12345"
, then str_num[::-1]
will be "54321"
, since the characters are different forwards and backwards.
If the string is the same forwards and backwards, we return True
to indicate that the number is a palindrome. Otherwise, we return False
to indicate that it is not a palindrome.
1 2 3 4 5 6 | if str_num == str_num[::-1]: return True else: return False |
That’s it! Now you can use this function to check if any number is a palindrome or not.