【问题标题】:restart loop after winning the game [duplicate]赢得比赛后重新开始循环[重复]
【发布时间】:2021-04-26 13:45:23
【问题描述】:
number = int(input("please choose your number: "))

while number != number_to_guess:
    if number > number_to_guess:
        number = int(input("Your guess is wrong it was bigger then the generated number, try again: "))
        continue
    if number < number_to_guess :
        number = int(input("Your guess was wrong it was smaller then the generated number, try again: "))

if number == number_to_guess:
    print("Congrats you won")
    restart = input("Do you want to play again? if yes type y, if not you can close the window \n")

while restart not in ["y"]:
    restart = input("please type y or close the window \n")

我希望它作为标题建议在用户键入 y 后重新启动,并且我希望它始终以数字输入“选择你的...”开头,但我不知道该怎么做

【问题讨论】:

    标签: python


    【解决方案1】:

    你可以在一个函数中编写代码,然后,如果你想重新启动,再次调用那个函数

    def game():
        number = int(input("please choose your number: "))
        number_to_guess = 5
    
        while number != number_to_guess:
            if number > number_to_guess:
                number = int(input("Your guess is wrong it was bigger then the generated number, try again: "))
                continue
            if number < number_to_guess :
                number = int(input("Your guess was wrong it was smaller then the generated number, try again: "))
    
        if number == number_to_guess:
            print("Congrats you won")
            restart = input("Do you want to play again? if yes type y, if not you can close the window \n")
            if restart == "y":          #restart the game
                game()
    
        while restart not in ["y"]:
            restart = input("please type y or close the window \n")
    
    # main code
    game()
    

    【讨论】:

      【解决方案2】:

      我们可以为此使用函数或while循环。

      有功能,

      def game():
         #implement game here
         number = input()
         #other stuff
      
      while True:
         game()
         restart = input()
         if restart != 'y':
            break # exit game
      

      注意:这是非常基本的逻辑,有关函数和循环的更多信息,请参阅教程here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-30
        • 1970-01-01
        • 1970-01-01
        • 2020-08-04
        • 2012-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多