Python Program to Check Palindrome: A Step-by-Step Guide

Python Palindrome Checker (Iterative Approach)

Using a character-by-character comparison loop to verify a palindrome.

How the Iterative Logic Works

Instead of reversing the whole string, this logic checks characters from both ends moving inward. We compare the first character with the last character, the second character with the second-to-last character, and so on.

The loop only needs to run up to the middle of the string. If any pair of characters does not match, the program instantly marks it as not a palindrome and stops checking. If the loop finishes without finding a mismatch, the string is confirmed to be a palindrome.

The Python Program

# This program checks if a string is a palindrome by comparing characters from outside inward.

# Accept user input string
user_input = input("Enter a string to check: ")

# Convert to lowercase to ensure character comparisons ignore casing
cleaned_string = user_input.lower()

# Determine the total length of the string
length = len(cleaned_string)

# Assume the string is a palindrome initially
is_palindrome = True

# Loop through the indices up to the midpoint of the string
for i in range(length // 2):
    # Compare character at index i with its mirrored character from the end
    if cleaned_string[i] != cleaned_string[length - 1 - i]:
        # A mismatch is found, so set the tracking flag to False
        is_palindrome = False
        # Exit the loop early since a single mismatch means it cannot be a palindrome
        break

# Check the result of the tracking flag after the loop
if is_palindrome:
    # Print confirmation if all matched
    print("The string is a palindrome!")
else:
    # Print alternative if a mismatch broke the loop
    print("The string is not a palindrome.")

Sample Inputs & Outputs

Execution walk-through of the character verification loop:

Input Value Step-by-Step Comparison Steps Program Output Result
"kayak" Compare index 0('k') with 4('k') -> Match.
Compare index 1('a') with 3('a') -> Match.
The string is a palindrome!
"RadAr" Cleaned to "radar".
Compare index 0('r') with 4('r') -> Match.
Compare index 1('a') with 3('a') -> Match.
The string is a palindrome!
"hello" Compare index 0('h') with 4('o') -> Mismatch!
Loop breaks immediately.
The string is not a palindrome.

Comments