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

Python中Blackjack游戏check_for_jack函数的and条件逻辑错误排查求助

问题分析与修复

你的代码问题出在条件表达式的逻辑写法错误,导致and运算符没有按你预期的方式工作。

为什么会出现这个问题?

在Python中,'ace' and "king" in user_deck这种写法并不是检查'ace'和"king"同时存在于user_deck中。原因有两点:

  1. 非空字符串(比如'ace')在布尔判断中会被直接判定为True。
  2. 运算符优先级:in的优先级比and高,所以这个表达式会被解析为('ace') and ("king" in user_deck)——也就是说,只要"king" in user_deck为真,不管'ace'是否在牌组里,整个条件都会被判定为真。

就像你给出的例子:当user_deck = ['jack', 'one']时,第三个elif的条件'ace' and "jack" in user_deck中,'ace'被判定为True,"jack" in user_deck也是True,所以整个条件成立,触发了错误的输出。

修复后的代码(优化版)

我们可以把构成Blackjack的大牌(king、queen、jack、ten)放到一个集合里,然后同时检查'ace'是否存在,以及牌组中是否包含任意一张大牌,这样代码更简洁,逻辑也更清晰:

def check_for_jack():
    # 定义能和ace组成Blackjack的大牌集合
    blackjack_high_cards = {"king", "queen", "jack", "ten"}
    
    # 检查玩家是否拿到Blackjack
    if 'ace' in user_deck and any(card in user_deck for card in blackjack_high_cards):
        print('You have a black jack, You win')
    # 检查电脑是否拿到Blackjack(仅当玩家没拿到时才判断)
    elif 'ace' in computer_deck and any(card in computer_deck for card in blackjack_high_cards):
        print('Computer has a black jack, You lose')

如果你想保留原有的分支结构(不优化)

那每个条件都要明确检查两个元素是否在牌组中,比如:

def check_for_jack(): 
    # user has jack 
    if 'ace' in user_deck and "king" in user_deck: 
        print('You have a black jack, You win') 
    elif 'ace' in user_deck and "queen" in user_deck: 
        print('You have a black jack, You win') 
    elif 'ace' in user_deck and "jack" in user_deck: 
        print('You have a black jack, You win') 
    elif 'ace' in user_deck and "ten" in user_deck: 
        print('You have a black jack, You win') 
    # computer has jack 
    elif 'ace' in computer_deck and "king" in computer_deck: 
        print('Computer has a black jack, You lose') 
    elif 'ace' in computer_deck and "queen" in computer_deck: 
        print('Computer has a black jack, You lose') 
    elif 'ace' in computer_deck and "jack" in computer_deck: 
        print('Computer has a black jack, You lose') 
    elif 'ace' in computer_deck and "ten" in computer_deck: 
        print('Computer has a black jack, You lose')

这样就能确保只有当'ace'和对应的大牌同时存在于牌组中时,才会触发对应的输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:13:11