首页 > 解决方案 > 如何在 python 中重置 while 循环,以使所有条件都与启动时相同?

问题描述

我正在尝试编写一个游戏:

我遇到的问题是,当用户猜到数字或丢失时,我无法弄清楚如何生成新的随机数并将罢工重置为零。

import random



game_stop = False

strikes = 0

random_list = [1,2,3,4,5,6,7,8,9,]

random_number = random.choice(random_list)

def play_again():
   play_again = input("play again?: ")
   if play_again == "yes":
       strikes = 0

       game_stop = False
       return random.choice(random_list)


while not game_stop:

   strikes = strikes + 1

   guess = input("enter guess: ")

   if guess == "exit":
       break

   if int(guess) > random_number:
       print("too high")
   elif int(guess) < random_number:
       print("too low")
   else:
       print("you guessed it!")
       print("It took you " + str(strikes) + " tries!")


       play_again()


   if strikes > 2:
       print("three strikes your out!")
       play_again()   '''

标签: pythonloopsreset

解决方案


修改你的 play_again() 函数,使用raw_input代替input

def play_again():
   play_again = raw_input("play again?: ")
   if play_again == "yes":
       strikes = 0

       game_stop = False
       return random.choice(random_list)

推荐阅读