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

Python布尔变量无法控制while循环,SIGKILL命令也无法终止执行

问题原因
  • 赋值运算符与比较运算符混用:你在gameplayint == "N"分支中写的Play == False是相等判断表达式,不会修改Play变量的值,因此Play仍然保持初始的True状态,自然会进入后续的while Play == True循环。同理gameplayint == "Y"分支中的Play == True也是无效的比较操作,没有赋值作用。
  • SIGKILL用法完全错误:signal.SIGKILL只是信号编号的常量,不是可调用函数,这段代码运行会直接抛出类型错误,无法实现你想要的终止程序效果。
  • 胜负判断逻辑是死循环:你用while anotherNum == False做胜负判断,该代码块内没有修改anotherNum值的逻辑,进入后会永远循环无法退出。
  • 重玩逻辑位置错误:目前重玩判断写在游戏主循环外,仅会执行一次,无法实现连续多局游玩的效果。
修复方案
  1. 把所有需要赋值的地方把==改成=,gameplayint == "N"分支赋值Play = False后直接终止程序即可,不需要调用信号。
  2. 删除错误的signal.SIGKILL(0)代码,需要退出程序直接调用exit()即可。
  3. 胜负判断不需要循环,把while anotherNum == False改成if anotherNum == False,仅执行一次判断逻辑。
  4. 把重玩逻辑移动到游戏主循环内部,实现多局游玩的效果,同时补全缺失的依赖库导入代码。
修正后可运行代码
import random
import time

# 变量初始化
Play = False
name = input("What's your name? ")
gameplayint = input(f"Very well then {name}, do you want to play 13? <Y or N> ")

if gameplayint == "N":
    print("What are you doing here then?")
    Play = False
    exit()
if gameplayint == "Y":
    Play = True
    time.sleep(0.5)
    print("We will start now.")
    print("")

# 游戏主循环
while Play == True: 
    pcNum = random.randint(1,19)
    anotherNum = True
    total = 0
    
    while anotherNum == True:
        playerNum = random.randint(1,10)
        total = 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> ")
        print("")
        if again == "Y":
            anotherNum = True
        else:
            anotherNum = False
            break
    # 单局结束,输出结果
    print("Computer got", pcNum)
    print("You got", total)
    # 胜负判断
    if anotherNum == False:
        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...")
    # 重玩判断
    again = input("Try again? <Y or N>")
    if again == "Y":
        Play = True
    else:
        Play = False
        print("Goodbye now.")

内容的提问来源于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 14:57:01