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

Python中exit命令未触发问题:循环计数判断逻辑错误

问题分析

你的代码问题出在continue语句上:当Player1获胜时,执行continue会直接跳回循环开头,完全跳过了后面检查counter1是否达到3的代码块。哪怕counter1已经加到3甚至更高,这部分判断逻辑永远没机会运行,自然不会触发退出。

修复方案

这里提供两种简单的修复方式,都能实现「Player1获胜次数≥3时退出」的需求:

方案一:在获胜后立即检查计数

把计数检查逻辑放到continue之前,这样每次Player1赢了之后,先判断是否达到退出条件,再决定是否继续循环:

counter1 = 0

while True:
  player1 = input("Player 1 > ")
  player2 = input("Player 2 > ")
  if player1 == "R" and player2 == "S":
    print("Player 1 wins")
    counter1 += 1
    print(counter1)
    # 获胜后立即检查是否达到退出条件
    if counter1 >= 3:
      print("Player 1 won the game")
      exit()
    continue
  else:
    print("Uhh.. try again")

方案二:移除continue,让每次循环都执行计数检查

去掉continue,这样不管Player1是否获胜,循环体最后都会执行计数检查逻辑:

counter1 = 0

while True:
  player1 = input("Player 1 > ")
  player2 = input("Player 2 > ")
  if player1 == "R" and player2 == "S":
    print("Player 1 wins")
    print(counter1)
    counter1 += 1
  else:
    print("Uhh.. try again")
  # 每次循环结束前都检查是否达到退出条件
  if counter1 >= 3:
    print("Player 1 won the game")
    exit()

另外建议把判断条件从counter1 ==3改成counter1 >=3,这样更稳妥,能避免因意外情况导致计数超过3才退出的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 09:57:13