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

Python开发21点(Blackjack)游戏输入N退出时while循环无法终止怎么办?

问题根因
  • 字符串比较大小写不匹配:你调用了lower()把用户输入转成全小写,却和大写的"N"、"Y"做比较。比如用户输入N,转小写后是"n","n" != "N"的结果为真,直接触发新开对局的逻辑,永远走不到终止循环的分支。
  • 条件分支逻辑冗余错误:第一个if已经过滤了所有不等于大写N的输入,剩下的只有输入等于大写N的情况,后续再判断!= "Y"完全没有必要,而且会导致输入非Y/N的异常字符时,逻辑不符合预期。
修正方案

把play_again对应的判断分支替换为如下代码即可:

play_again = input("\nDo you want to play another round? Y/N: ")
# 统一用小写字符判断,逻辑更清晰
if play_again.lower() == "y":
    print("You wanted to play another round, you will be dealt two new cards.\n")
    player_hand.clear()
    dealer_hand.clear()
    give_cards(player_hand, 2)
    give_cards(dealer_hand, 2)
    # 额外修复:新开对局需要重新计算手牌总点数,否则会沿用旧值
    player_total = bjm.calculate_hand_value(player_hand)
    dealer_total = bjm.calculate_hand_value(dealer_hand)
    print(f'\nThe players new cards are: {" and a ".join(player_hand)}, with a total value of {player_total}.')
    print(f'The dealers new cards are: {" and a ".join(dealer_hand)}, with a total value of {dealer_total}.')
else:
    # 只要输入不是y就直接退出
    closed = True

额外说明:原代码新开对局后没有重新计算player_total和dealer_total,会导致打印的总点数还是上一局的数值,属于隐藏bug,上述代码已经同步修复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:15:00