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

Python编写石头剪刀布游戏时while循环内elif语句被跳过如何解决?

问题原因及解决方案

1. 核心逻辑错误:条件判断写法不正确

你写的if replay == "N" or "n"是Python新手常见的语法误区:

  • 该表达式会被解析为 (replay == "N") or ("n")
  • 非空字符串"n"的布尔值恒为True,因此整个if条件永远成立,不管你输入什么都会直接触发退出逻辑
  • Y对应的elif判断也存在同样的写法问题

2. 循环逻辑冗余

当前while循环的结构已经会在每次循环开始时自动调用game(),你在elif判断用户要重玩时额外调用game(),会导致每次重玩需要连续玩两次,属于多余逻辑。

修正后的完整代码

import random

def game():
    sl = ["rock", "paper", "scissors"]
    us = input("Rock, paper, scissors?: ")
    sl.remove(us)
    pcs = random.choice(sl)

    if us == "rock" and pcs == "paper":
        print("You chose " + us + ". PC chose " + pcs + ". You lose.")
    elif us == "rock" and pcs == "scissors":
        print("You chose " + us + ". PC chose " + pcs + ". You win.")
    if us == "paper" and pcs == "rock":
       print("You chose " + us + ". PC chose " + pcs + ". You win.")
    elif us == "paper" and pcs == "scissors":
        print("You chose " + us + ". PC chose " + pcs + ". You lose.")
    if us == "scissors" and pcs == "rock":
        print("You chose " + us + ". PC chose " + pcs + ". You lose.")
    elif us == "scissors" and pcs == "paper":
        print("You chose " + us + ". PC chose " + pcs + ". You win.")

while True:
    game()
    replay = input("Would you like to play again? Y/N ")
    # 优化判断逻辑,统一转小写后比较更简洁
    if replay.lower() == "n":
        print ("ciaox")
        break
    elif replay.lower() == "y":
        # 无需额外调用game(),循环会自动回到开头执行
        continue

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:27:04