Exercise
Iterative Palindrome Function
Objective
Develop a Python program with an iterative function to check if a string is a palindrome (symmetric). For instance, "RADAR" is considered a palindrome.
Example Python Exercise
Show Python Code
# Function to check if a string is a palindrome using iteration
def is_palindrome(s):
# Convert the string to lowercase to make the check case-insensitive
s = s.lower()
# Loop through the string from both ends towards the middle
for i in range(len(s) // 2):
# Compare characters at the start and end positions
if s[i] != s[len(s) - i - 1]:
return False # Return False if characters don't match
return True # Return True if the string is a palindrome
# Example strings to test
test_strings = ["RADAR", "hello", "madam", "world"]
# Check if each string is a palindrome
for test_string in test_strings:
result = is_palindrome(test_string)
print(f"Is '{test_string}' a palindrome? {result}")
Output
python palindrome_check.py
Is 'RADAR' a palindrome? True
Is 'hello' a palindrome? False
Is 'madam' a palindrome? True
Is 'world' a palindrome? False
Share this Python Exercise