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

Python中exit()与while循环冲突:如何终止外层函数而非整个脚本

解决Blackjack游戏中提前终止game()函数的问题

别用exit(),它会直接终止整个脚本。给你几个可行的方案,既能终止外层game()函数,又不影响重复游玩的循环:

方案1:自定义异常触发游戏结束

自定义一个专门的异常类,在需要终止游戏的地方抛出异常,外层game()捕获后直接return退出,不影响外层循环。

# 定义游戏结束的专属异常
class GameEnd(Exception):
    pass

def game():
    player = [10, 11]  # 示例手牌
    dealer = [9, 10]

    def first_check():
        player_sum = sum(player)
        dealer_sum = sum(dealer)
        if 21 in [player_sum, dealer_sum]:
            if player_sum == 21 and dealer_sum == 21:
                print("Both you and the dealer have Blackjack, its a push!!")
            # 抛出异常替代exit()
            raise GameEnd

    try:
        first_check()
        # 这里写game()原本的后续逻辑(玩家拿牌、庄家操作等)
        print("游戏继续进行...")
    except GameEnd:
        # 捕获异常后直接退出game()
        return

# 外层重复游玩循环保持不变
while True:
    game()
    if "n" in input("Do you want to play again? Y or N").lower():
        break

方案2:让嵌套函数返回终止标记

修改嵌套函数,让它返回布尔值告知外层game()是否需要终止。game()检查返回值后,决定是否直接退出。

def game():
    player = [10, 11]
    dealer = [9, 10]

    def first_check():
        player_sum = sum(player)
        dealer_sum = sum(dealer)
        if 21 in [player_sum, dealer_sum]:
            if player_sum == 21 and dealer_sum == 21:
                print("Both you and the dealer have Blackjack, its a push!!")
            # 返回True表示需要终止游戏
            return True
        # 不需要终止则返回False
        return False

    # 调用嵌套函数后判断是否终止
    if first_check():
        return
    # 后续游戏逻辑
    print("游戏继续进行...")

while True:
    game()
    if "n" in input("Do you want to play again? Y or N").lower():
        break

方案3:简化结构,合并嵌套逻辑

如果嵌套函数只是做简单检查,直接把逻辑整合到game()里,用return就能直接终止game(),避免嵌套函数的层级问题。

def game():
    player = [10, 11]
    dealer = [9, 10]

    # 把first_check的逻辑直接放到game()中
    player_sum = sum(player)
    dealer_sum = sum(dealer)
    if 21 in [player_sum, dealer_sum]:
        if player_sum == 21 and dealer_sum == 21:
            print("Both you and the dealer have Blackjack, its a push!!")
        # 直接return终止game()
        return

    # 后续游戏逻辑
    print("游戏继续进行...")

while True:
    game()
    if "n" in input("Do you want to play again? Y or N").lower():
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:55:24