求助:Python回文判断代码异常,输入'race'误判为TRUE
Hey there! Let's dig into why your code is giving the wrong result for inputs like "race".
The Root Problem
Your current logic has a critical flaw: every time it finds a matching pair of characters, it overwrites the b variable to "TRUE"—even if it already found a mismatch earlier. For "race", here's what happens step by step:
- First loop iteration: compares 'r' (index 0) with 'e' (index 3) → mismatch, so
b = "FALSE" - Second iteration: compares 'r' (index 0) with 'c' (index 2) → mismatch,
b stays "FALSE" - Third iteration: compares 'r' (index 0) with 'a' (index 1) → mismatch,
b stays "FALSE" - Fourth iteration: compares 'r' (index 0) with 'r' (index 0) → match, so
b gets set to "TRUE"
That final match overwrites the correct "FALSE" result, which is why you're seeing the wrong output.
Fixed Version of Your Original Code
We can fix this by:
- Starting with a default assumption that the string is a palindrome
- Immediately marking it as not a palindrome and stopping the loop as soon as a mismatch is found
- Only comparing the first half of the string to the second half (no need to check every character twice)
string = input("Please enter any word: ") a = 0 string_length = len(string) is_palindrome = True # Start with the assumption it's a palindrome # Only loop through the first half of the string for string_index in range(string_length - 1, string_length // 2 - 1, -1): character = string[string_index] if string[a] != character: is_palindrome = False break # No need to check further once a mismatch is found a += 1 print("TRUE" if is_palindrome else "FALSE")
A More Pythonic Approach
If you want a simpler solution, Python lets you reverse a string in one line with slicing. This is clean and efficient:
string = input("Please enter any word: ") is_palindrome = string == string[::-1] print("TRUE" if is_palindrome else "FALSE")
Here, string[::-1] creates a reversed copy of the original string. We just compare the two—if they're identical, it's a palindrome!
内容的提问来源于stack exchange,提问作者Mehdi Rizvi

