Checking for Palindrome Numbers in Python
A palindrome is a number (or word) that remains the same when its digits (or letters) are reversed. For example, the number 121 is a palindrome, while 123 is not. This function checks if a given integer is a palindrome.
Function Definition
Below is a Python function that takes an integer as input and returns True if the number is a palindrome and False otherwise.
def is_palindrome(number):
# Convert the number to a string to check for palindrome property
num_str = str(number)
# Compare the string with its reverse
return num_str == num_str[::-1]
How the Function Works
1. String Conversion: The function converts the integer to a string using str().
2. Reverse Comparison: It then checks if the string is equal to its reverse. The slice notation [::-1] is used to create the reversed string.
3. Return Value: The function returns True if the original string matches the reversed string, otherwise it returns False.
Example Usage
print(is_palindrome(121)) # Output: True
print(is_palindrome(-121)) # Output: False
print(is_palindrome(10)) # Output: False
print(is_palindrome(12321)) # Output: True
Notes
- The function handles negative numbers by default, as the negative sign would make such numbers non-palindromic.
- It is efficient for typical usage, working well with positive and negative integers of reasonable sizes.
This simple function serves as a practical example of using string manipulation and comparison in Python to solve common programming problems.