Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

Have a look at the below code, which will check whether a word is palindrome or not.

str = input("Enter the string")

l = len(str)

p = l-1

index = 0

while index < p:

    if str[index] == str[p]:

        index = index + 1

        p = p-1

        print("String is a palindrome")

        break

    else:

        print("string is not a palindrome")

On the off chance that a word is inputted, for instance, I need the program to check whether this word is a palindrome and give yield as "The given word is a palindrome". 

However, I'm confronting a difficulty that, the program checks first r and r and prints "The given word is a palindrome" and afterward checks o and o and prints "The given word is a palindrome". It prints the outcome the same number of times as it is checking the word. 

I need the outcome to be conveyed just a single time. How to change the code?

1 Answer

0 votes
by (26.4k points)

Try the following code:

string_to_check = input("Enter a string")

if string_to_check == string_to_check[::-1]:

    print("This is a palindrome")

else:

    print("This is not a palindrome"

Here, I'm just reversing it, then comparing it with the original

Want to learn python in detail? Come and Join python course to gain more knowledge

Watch this video tutorial on how to become a professional in python:

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...