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

Python随机语录来源验证问题求助:输入匹配始终显示错误

问题:语录来源验证逻辑错误,无论输入对错都显示错误

核心问题分析

  1. 逻辑结构错误
    你写了两个独立的if语句,当第一个if匹配成功(比如用户答对了Kingdom Hearts),第二个if必然不成立,会直接执行else分支输出"Incorrect",导致正确的判断被覆盖。

  2. 换行符干扰
    从txt文件读取每一行时,字符串会保留末尾的\n换行符。虽然打印时看不到这个符号,但直接做字符串相等判断时,会因为这个隐藏的换行符导致匹配失败。

修正后的代码

import os
import sys
import random

# 读取文件时去掉换行符,避免干扰判断
with open(os.path.join(sys.path[0], "alanwake.txt"), "r", encoding='utf8') as txt1:
    wake = [line.rstrip('\n') for line in txt1]

with open(os.path.join(sys.path[0], "kh.txt"), "r", encoding='utf8') as txt2:
    kh = [line.rstrip('\n') for line in txt2]

# 用元组存储语录和对应的来源,后续判断更直观
quote_options = [
    (random.choice(kh), "kingdom hearts"),
    (random.choice(wake), "alan wake")
]
quote, correct_source = random.choice(quote_options)

print(quote)
print("Is this quote from Kingdom Hearts or Alan Wake?")
inp = input().lower()

# 用单分支判断,避免逻辑覆盖
if inp == correct_source:
    print("Correct!")
else:
    print("Incorrect")

代码说明

  • 读取文件时用line.rstrip('\n')去除每行末尾的换行符,保证字符串判断的准确性。
  • 用元组(语录, 来源)的形式存储选项,直接绑定语录和对应的正确来源,避免了通过列表索引判断的复杂逻辑。
  • 改用单分支对比用户输入和正确来源,逻辑更清晰,不会出现分支覆盖的问题。

内容的提问来源于stack exchange,提问作者nerveship

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:31:12