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

Python无限循环中选选项1后隐藏选项3的实现咨询

解决方案:用状态变量+条件判断实现选项动态隐藏

完全可以用if-else实现这个需求,核心是新增一个状态变量追踪用户是否已经执行过Hit操作(选项1),然后根据这个变量动态决定是否打印选项3。

修改后的代码示例

假设这段逻辑处于无限循环中(比如while running:),调整后的代码如下:

# 在循环外初始化状态变量
has_hit = False
running = True

while running:
    self.blackjack = False
    print(f" Press 1 For Hit a New Card ")
    print(" Press 2 For Stand ")
    # 只有用户没选过Hit时才显示选项3
    if not has_hit:
        print(" Press 3 for Double ")
    
    choice = int(input(" Enter Your Choice: "))
    if choice == 1:
        running = self.hitTheCard()
        # 标记用户已经执行过Hit操作
        has_hit = True
    elif choice == 2:
        self.stand()
        running = False
    elif choice == 3:
        self.betAmount *= 2
        running = self.hitTheCard()
        self.player.displayCardInHand()
        if running:
            self.stand()
            running = False
    else:
        print(" Invalid choice given try again.")

关键修改点

  • 新增has_hit布尔变量,初始值为False,用来记录用户是否选过选项1
  • 将打印选项3的语句放在if not has_hit分支内,确保只有首次选择(或未选过Hit)时才显示该选项
  • 当用户选择选项1后,立即将has_hit设为True,后续循环迭代时就不再显示选项3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 14:10:41