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

Python中布尔值控制的while循环无条件重复运行问题排查

错误原因

  • 核心问题是混淆了Python中的赋值运算符=和相等比较运算符==。你代码里给anotherNum赋值的两行都写成了==,这行代码只会判断anotherNum是否等于后面的值,不会真正修改它的数值。只要你初始化时anotherNum设为True,循环条件就永远成立,自然不会进入后续的游戏结束逻辑。
  • 其次你对用户输入的判断只匹配了大写Y,输入小写y、n或者大写N时都会进入else分支,哪怕你写了break语句,如果因为赋值逻辑失效、缩进错误没触发break,循环就会一直执行。
  • 从你给出的运行输出看total没有累加,每次都是新生成的点数数值,说明你大概率把total的初始化代码写在了while循环内部,每次循环都会把total重置为初始值,看起来就像跳过了total = total + playerNum语句。

修复后代码

import random
# 变量初始化必须放在循环外部
total = 0
pcNum = random.randint(1, 13)
name = "玩家"
anotherNum = True

while anotherNum:
    playerNum = random.randint(1,10)
    total += playerNum
    print("")
    print("Your number is ", str(playerNum) + ".")
    print("You have " + str(total) + " in total.")
    print("")
    # 输入转为大写,兼容大小写输入
    again = input("Roll another number? <Y or N> ").strip().upper()
    print("")
    if again == "Y":
        anotherNum = True
    else:
        anotherNum = False

# game finished now
print("Computer got", pcNum)
print("You got", total)
# 判定胜负的逻辑不需要写while循环,因为只会执行一次,直接写判断即可
if (total <= 13) and (total > pcNum): 
    print("You,", name, "have won!")
elif (pcNum <= 13) and (pcNum > total):
    print("The computer has bested you,", name + "!")
else:
    if (total == pcNum) and (total <= 13):
        print("Draw...")
    elif (pcNum > 13) and (total <= 13):
        print("You,", name + " have won!")
    else:
        print("Both of you have lost. Wow...")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:15:01