Member-only story

num = input("Enter a number: ")

if num == num[::-1]:
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")

1. num = input("Enter a number: ")

  • Purpose: Prompts the user to input a number.
  • Result: Stores the user’s input as a string in the variable num.
  • Example: If the user enters 121, then num is "121" (a string, not an integer).

2. if num == num[::-1]:

  • Purpose: Compares the string num with its reverse (num[::-1]).
  • num[::-1]: This uses Python slicing to reverse the string.

Syntax:

  • [::-1]: Start from the end of the string and move backward (reverse the order).

Example:

  • If num = "121", then num[::-1] = "121".
  • If num = "123", then num[::-1] = "321".

Comparison:

  • If num is the same as num[::-1], the input is a palindrome.
  • Otherwise, it is not a palindrome.

3. print(f"{num} is a palindrome.")

  • If the condition num == num[::-1] is True, this statement is executed.

Example:

  • Input: "121"
  • Output: 121 is a palindrome.

4. else: print(f"{num} is not a palindrome.")

  • If the condition num == num[::-1] is False, this statement runs.

Example:

  • Input: "123"
  • Output: 123 is not a palindrome.

--

--

Python Coding
Python Coding

Written by Python Coding

Learn python tips and tricks with code I Share your knowledge with us to help society. Python Quiz: https://www.clcoding.com/p/quiz-questions.html

No responses yet