如何在python中重置while循环,以便所有条件都与启动时相同?

问题描述 投票:-1回答:1

我正在尝试编写以下游戏:

  • 绘制随机数
  • 要求用户输入猜测
  • 如果猜测值太低或太高,则会相应地打印一条语句
  • 如果用户打印的猜测超过3个(“三击出局”)
  • 如果用户猜到它会打印(“您猜到了”)
  • 在两种情况下,它都会询问用户是否要再次播放。
  • 如果是,则程序应生成新的数字,并且打击次数应返回零
  • 如果不,请中断

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

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()   '''
python loops reset
1个回答
0
投票

修改您的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)
© www.soinside.com 2019 - 2024. All rights reserved.