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

如何阻止Python while语句在if条件满足时仍输出错误信息?

问题原因

代码逻辑顺序错误,while循环内没有对输入结果做判断就直接打印错误提示:只要进入循环读取用户输入后,不管输入内容是否匹配字典中的shadow名称,都会执行错误打印语句,因此正确输入也会先输出错误提示再执行后续正确逻辑。

修复后代码

import time

print("Hello, welcome to the Persona 5 Helper")
time.sleep(2)
print("Type in the name of the shadow you're facing and the app will show you its weaknesses\n")
time.sleep(2)

shadows = {"Crypt-dwelling Demon": "Jack-O lantern\n" "Version P5: Inherit = Fire, Reflects = N\A, Absorbs = Fire, Block = N\A, Resists = N\A, Weak = Gun/Ice/Wind\n"
                                   "Version P5R: Inherit = N\A, Reflects = N\A, Absorbs = Fire, Block = N\A, Resists = N\A, Weak = Ice/Wind",
           "Beguiling Girl": "Pixie\n" "Version Both: Inherit = Elec, Reflects = N\A, Absorbs = N\A, Block = N\A, Resists = Elec/Bless, Weak = Gun/Ice/Curse",
           "Bedside Brute": "Incubus\n" "Version Both: Inherit = Ailment, Reflects = N\A, Absorbs = N\A, Block = N\A, Resists = Elec, Weak = Gun/Bless",
           "Gallows Flower": "Mandrake\n" "Version Both: Inherit = Elec, Reflects = N\A, Absorbs = N\A, Block = N\A, Resists = Elec/Bless, Weak = Wind",
           "Dirty Two-horned Beast": "Bicorn\n" "Version Both: Inherit = Wind, Reflects = N\A, Absorbs = N\A, Block = N\A, Resists = Curse, Weak = Elec",
           "Apprentice in a jug": "Agathion\n" "Version Both: Inherit = Elec, Reflects = N\A, Absorbs = N\A, Block = N\A, Resists = Elec/Gun, Weak = Wind"}

shadowName = ""

while shadowName not in shadows:
    shadowName = input("Name of shadow: ")
    # 仅在输入不匹配时输出错误提示
    if shadowName not in shadows:
        print('ERROR: Make sure your spelling is correct or the shadow is an existing one...')

print("Shadow Identified...")
print(shadows[shadowName])

优化说明

原代码中退出while循环的条件就是shadowName存在于字典中,因此后续不需要再加if shadowName in shadows的判断,可以直接打印识别结果,减少冗余判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 11:15:04