如何让指定Python脚本执行结束后自动重复运行?
Got it! Let's tweak your script so it runs again automatically after showing whether you won or lost. Here are two simple, common ways to do this:
方法1:无限循环(直到手动停止)
This will keep the game going forever until you press Ctrl+C to stop the program:
import random my_list = "123456789" # 原代码里的括号其实没必要,字符串直接写更简洁,功能完全一样 while True: player = input("number? - ") if player == random.choice(my_list): print("you win") else: print("you lose") # 循环会自动回到开头,重新运行游戏逻辑
方法2:让用户选择是否继续
If you want to let the player decide when to stop playing, add a prompt after each round:
import random my_list = "123456789" while True: player = input("number? - ") if player == random.choice(my_list): print("you win") else: print("you lose") # 询问是否继续游戏 play_again = input("Want to play again? (y/n): ").lower() if play_again != 'y': print("Thanks for playing!") break # 退出循环,结束程序
小细节提醒
Your original code uses my_list = ("123456789") — just a heads-up that this creates a string, not a tuple. If you intended to make a tuple, you'd need to add a comma at the end like ("123456789",), but since random.choice works perfectly with strings (they're iterable!), this doesn't break your game at all. I just simplified it in the examples for clarity.
内容的提问来源于stack exchange,提问作者Abel

