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

Python入门求助:如何用while循环让程序回到开头重新运行?

解决石头剪刀布游戏的循环重玩问题

你当前的代码核心问题是:游戏的核心逻辑(玩家选择、电脑出拳、胜负判断)都在while循环外部,只有询问是否再玩的代码在循环里,所以输入"yes"后只会重复提问,不会重新触发游戏流程。

正确的做法是把完整的游戏逻辑都放进while循环内部,让每次循环都执行一轮完整的游戏,最后再询问是否继续。同时可以优化输入处理,兼容大小写输入,提升用户体验。

修改后的完整代码

import random

play_again = "yes"
while play_again.lower() == "yes":
    # 处理玩家输入,兼容大小写和前后空格
    Player_1 = input("Choose Rock, Paper, or Scissors: ").strip().capitalize()
    
    # 电脑随机出拳
    computer_choices = ["Rock", "Paper", "Scissors"]
    computer_move = random.choice(computer_choices)
    print(f"Computer chose: {computer_move}")
    
    # 胜负判断逻辑
    if Player_1 == computer_move:
        print("Both players chose the same thing. The game is a draw!")
    elif Player_1 == "Rock":
        print("Player with Rock wins!" if computer_move == "Scissors" else "Player with Paper wins!")
    elif Player_1 == "Paper":
        print("Player with Paper wins!" if computer_move == "Rock" else "Player with Scissors wins!")
    elif Player_1 == "Scissors":
        print("Player with Scissors wins!" if computer_move == "Paper" else "Player with Rock wins!")
    else:
        # 处理玩家输入无效的情况
        print("Invalid choice! Please enter Rock, Paper, or Scissors.")
    
    # 询问是否继续游戏
    play_again = input("Do you want to play again? (yes/no): ")

关键改动说明

  1. 循环范围调整:将所有游戏相关代码放入while循环内,确保每次循环都完整执行一轮游戏流程
  2. 输入优化:用strip().capitalize()处理玩家输入,兼容rock、ROCK、rock等各种输入格式
  3. 无效输入处理:新增了错误提示,避免玩家输入不符合要求的内容时无反馈
  4. 代码简化:将嵌套的if-else简化为三元表达式,让胜负判断逻辑更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:44:59