π Day 63/150 – Check Palindrome String in Python
A palindrome string reads the same forward and backward.
Examples:
- "madam" ✅
- "racecar" ✅
- "python" ❌
Let’s explore different ways to check palindrome strings in Python π
πΉ Method 1 – Using Slicing
text = "madam" if text == text[::-1]: print("Palindrome") else: print("Not Palindrome")
✅ Simple and most commonly used method.
πΉ Method 2 – Using for Loop
text = "madam" reversed_text = "" for ch in text: reversed_text = ch + reversed_text if text == reversed_text: print("Palindrome") else: print("Not Palindrome")
✅ Manually reverses the string using a loop.
πΉ Method 3 – Using while Loop
text = "madam" start = 0 end = len(text) - 1 is_palindrome = True while start < end: if text[start] != text[end]: is_palindrome = False break start += 1 end -= 1 print("Palindrome" if is_palindrome else "Not Palindrome")
✅ Compares characters from both ends.
πΉ Method 4 – Taking User Input
text = input("Enter a string: ") if text == text[::-1]: print("Palindrome") else: print("Not Palindrome")
✅ Useful for real-time user input.
πΉ Method 5 – Using Function
def is_palindrome(text): return text == text[::-1] text = "madam" print("Palindrome" if is_palindrome(text) else "Not Palindrome")
✅ Reusable and clean approach.
π Key Takeaways
- [::-1] is the easiest way to reverse a string.
- Palindrome means same forward and backward.
- Loops help understand the internal logic better.
- Functions make code reusable and cleaner.


0 Comments:
Post a Comment