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

如何让Python程序运行结束后自动重启?以石头剪刀布程序为例

解决石头剪刀布程序的重复运行问题

Hey there! Let's tackle your two questions about making your Rock-Paper-Scissors game replayable. Here's how you can do it:

1. 让Python程序运行结束后重新运行

最实用的方法是用循环结构包裹整个游戏流程,这样程序完成一局后不会直接终止,而是回到游戏起点重新执行。你可以选择无限循环+退出选项的模式,既灵活又友好。

2. 让程序自动重启,无需重新运行代码再次游玩

这个需求的核心解法和上面一致——通过循环实现游戏的重复执行,同时添加玩家选择环节,不用重新启动脚本就能继续游玩。

修改后的完整代码

import random

# 用无限循环包裹游戏逻辑,实现重复运行
while True:
    game = ["Rock", "Paper", "Scissors"]
    choice = random.choice(game)
    question = input("Choose one (Rock/Paper/Scissors) : ")
    
    # 原有的胜负判断逻辑
    if question == choice:
        print(f'I chose {choice}')
        print("We got the same thing! Try again")
    elif question == "Rock" and choice == "Paper":
        print(f'I chose {choice}')
        print("I win!")
    elif question == "Paper" and choice == "Rock":
        print(f'I chose {choice}')
        print("You win!")
    elif question == "Rock" and choice == "Scissors":
        print(f'I chose {choice}')
        print("You win!")
    elif question == "Scissors" and choice == "Rock":
        print(f'I chose {choice}')
        print("I win!")
    elif question == "Scissors" and choice == "Paper":
        print(f'I chose {choice}')
        print("You win!")
    elif question == "Paper" and choice == "Scissors":
        print(f'I chose {choice}')
        print("I win!")
    else:
        print("Invalid input! Please enter Rock, Paper, or Scissors.")
    
    # 询问玩家是否继续游玩
    play_again = input("Want to play again? (y/n): ").lower()
    if play_again != 'y':
        print("Thanks for playing!")
        break  # 跳出循环,终止程序

关键改动说明

  • while True 创建了一个无限循环,游戏的所有核心逻辑都在循环内部,每完成一局就会回到循环开头,准备下一轮游戏。
  • 新增的play_again输入询问,让玩家可以自主选择继续或退出,避免程序无限制运行。
  • 添加了else分支处理无效输入,提升了游戏的容错性和用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:31:13