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

如何实现不同语句多条件循环,条件不满足时持续执行及代码问题修复

问题修复说明

你的代码存在4处核心错误,修改后可正常运行:

  • 变量未初始化:weapon_1 没有预先赋值就调用了strip()方法,会直接抛出NameError
  • 变量赋值逻辑错误:后续给三个武器变量赋值时,你全部用weapon_1的值覆盖了原本的正确取值
  • 循环条件逻辑错误:多条件判断写法不符合Python语法规则,!=不能连写多个or后的变量,非空字符串的布尔值永远为True,会导致循环条件永远成立
  • 流程顺序错误:先判断输入有效性再执行循环的顺序颠倒,且循环内部没有判断输入合法后退出的逻辑

修复后可运行代码

# 先初始化三个合法武器的值
weapon_1 = "sword"
weapon_2 = "axe"
weapon_3 = "spiked club"

while True:
    weapon = input("请选择一种武器:剑、斧头、钉头锤\n")
    weapon = weapon.strip().lower()
    # 批量判断是否属于合法取值
    if weapon in (weapon_1, weapon_2, weapon_3):
        print("选得好!我也会选{}!".format(weapon))
        # 输入合法直接退出循环
        break
    # 不合法就提示后重新循环
    print("选项无效。")

如果你需要保留原有写法的结构,只做错误修复,可参考如下版本:

weapon_1 = "sword"
weapon_2 = "axe"
weapon_3 = "spiked club"

weapon = input("请选择一种武器:剑、斧头、钉头锤\n")
weapon = weapon.strip().lower()

if weapon == weapon_1:
    print("选得好!我也会选{}!".format(weapon))
elif weapon == weapon_2:
    print("选得好!我也会选{}!".format(weapon))
elif weapon == weapon_3:
    print("选得好!我也会选{}!".format(weapon))

# 修复循环条件,判断不在合法列表内就继续循环
while weapon not in (weapon_1, weapon_2, weapon_3):
    print("选项无效。")
    weapon = input("请选择一种武器:剑、斧头、钉头锤\n")
    weapon = weapon.strip().lower()
    # 重新输入后判断合法就输出提示
    if weapon in (weapon_1, weapon_2, weapon_3):
        print("选得好!我也会选{}!".format(weapon))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:36:02