You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:Python回文判断代码异常,输入'race'误判为TRUE

Fixing Your Palindrome Check Code

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:

  1. First loop iteration: compares 'r' (index 0) with 'e' (index 3) → mismatch, so b = "FALSE"
  2. Second iteration: compares 'r' (index 0) with 'c' (index 2) → mismatch, b stays "FALSE"
  3. Third iteration: compares 'r' (index 0) with 'a' (index 1) → mismatch, b stays "FALSE"
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:56:22