In this code, we are going to discuss how to check if a given string is a palindrome using a while loop in python.
This program checks whether a given string is a palindrome or not using a while loop.
Simple code:
string = input("Enter a string: ")
i = 0
j = len(string)-1
flag = True
while(i<j):
if(string[i] != string[j]):
flag = False
break
i += 1
j -= 1
if(flag):
print(string, "is a palindrome.")
else:
print(string, "is not a palindrome.")
Output:
Enter a string: noon
noon is a palindrome.
Code with explanation:
# Ask the user to enter a string
string = input("Enter a string: ")
# Initialize the start and end indices of the string
i = 0
j = len(string)-1
# Initialize a flag variable to store if the string is a palindrome or not
flag = True
# Use a while loop to compare the characters of the string from both ends
while(i<j):
# If the characters at i and j are not equal, set the flag to False and break out of the loop
if(string[i] != string[j]):
flag = False
break
# Increment i and decrement j for the next comparison
i += 1
j -= 1
# Check the flag variable to see if the string is a palindrome and print the result
if(flag):
print(string, "is a palindrome.")
else:
print(string, "is not a palindrome.")
Explanation:
- The program prompts the user to enter a string using the input() function.
- Two indices i and j are initialized at the start and end of the string, respectively.
- A flag variable is initialized to True.
- The while loop is used to compare the characters from both ends of the string. If characters at the current indices are not equal, the flag is set to False and the loop is broken.
- At each iteration, i and j are incremented and decremented, respectively, to move toward the center of the string.
- Finally, the flag variable is checked to determine if the string is a palindrome, and an appropriate message is printed using the print() function.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.