Skip to content
Programs · Program 8-5

Q.Program 8-5: Write a program using a user defined function to check if a string is a palindrome or not. (A string is called palindrome if it reads same backwards as forward. For example, Kanak is a palindrome.)

Tamil Nadu DgeTextbookSubjective· 3mImportance★★★★★est
46% · 6/13 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

A palindrome reads the same both ways, so compare the first character with the last, the second with the second-last, moving inwards — the first mismatch proves it is not a palindrome; if the pointers cross with no mismatch, it is. Case-fold first so "Kanak" qualifies.

Idea. Rather than building the reversed string and comparing, the classic two-pointer method checks the defining property directly: st[0] must equal st[-1], st[1] must equal st[-2], and so on. Two index variables i (front) and j (rear) walk toward each other. Since the book counts "Kanak" as a palindrome, we convert the input to lowercase before checking — otherwise 'K' vs 'k' would fail.

def checkPalindrome(st):
    """Return True if st is a palindrome, else False."""
    i = 0
    j = len(st) - 1
    while i < j:
        if st[i] != st[j]:
            return False       # a mismatch settles it immediately
        i += 1
        j -= 1
    return True                # pointers met/crossed: all pairs matched

# main program
st = input("Enter a string: ")
st = st.lower()                # treat 'K' and 'k' as the same letter
if checkPalindrome(st):
    print("The given string", st, "is a palindrome")
else:
    print("The given string", st, "is not a palindrome")

Trace for st = "kanak" (indices 0–4):

Stepijst[i]st[j]Match?
104kkyes → move in
213aayes → move in
322——i < j is False → loop ends

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.