palindrome string program in python using for loop

In this article let's try to find out if the given string is palindrome or not using the for loop.  given a string you have to find if it is palindrome or not. That is Reverse of a string matches with the string itself or not using a Python program.

 

palindrome string program in python using for loop

 



palindrome string program in python using for loop


lets ask a user to enter a string using input function call and get the length of the string using length function call.

text = input("Enter a String : ")
length = len(text)

Once we get the input string and the string length,  let's use the following two for loop to to iterate from the starting of the string to end of the string using a range function call and get the index or offset.

Once we get the index, take each and every character of a string and compare it with the end of the string.  If it is not matching print that string is not a palindrome and break that for loop. Use the for loop else part to print the string is palindrome.

Note: text[length - 1 - index] will give reverse character of a given index

for index in range(length):
   if text[index] != text[length-1-index]:
       print("String is Not a Palindrome")
       break
else:
   print("String is Palindrome")

This completes the program to check if the given string is palindrome or not using the for loop and compare each and every index with the last index of string

Final program
=================================

text = input("Enter a String : ")

length = len(text)
for index in range(length):
   if text[index] != text[length-1-index]:
       print("String is Not a Palindrome")
       break
else:
   print("String is Palindrome")




OUTPUT:
====================

Enter a String : hello
String is Not a Palindrome

Enter a String : madam
String is Palindrome

Enter a String : malayalam
String is Palindrome

Enter a String : hindi
String is Not a Palindrome


Conclusion : Try running a program, comment down below if you have any queries.

Post a Comment

0 Comments