Python

Palindrome Number in Python using Function2 min read

Here’s an example Python function that checks if a number is a palindrome or not:

Here’s how you can use this function to check if a number is a palindrome:




This will output:

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.

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.

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.

That’s it! Now you can use this function to check if any number is a palindrome or not.

Leave a Comment