如何询问用户是否要再次播放并重复while循环?

Liz*_*zie 2 python loops nested while-loop

在Python上运行,这是我的代码示例:

import random 

comp = random.choice([1,2,3])

while True:
     user = input("Please enter 1, 2, or 3: ")
     if user == comp
             print("Tie game!")
     elif (user == "1") and (comp == "2")
             print("You lose!")
             break
     else:
             print("Your choice is not valid.")
Run Code Online (Sandbox Code Playgroud)

因此,这部分工作。但是,我如何退出此循环,因为在输入正确的输入后,它会一直询问“请输入1,2,3”。

我还想问一下玩家是否想再次玩:

伪代码:

     play_again = input("If you'd like to play again, please type 'yes'")
     if play_again == "yes"
         start loop again
     else:
         exit program
Run Code Online (Sandbox Code Playgroud)

这与嵌套循环有关吗?

Din*_*kar 5

您的代码要点:

  1. 您粘贴的代码':'在之后if,elif和之后都没有else.
  2. 您可以使用诸如的控制流语句来实现所需的一切continue and break请在此处查看更多详细信息
  3. 您需要从“ YOU LOSE”中删除休息时间,因为您想询问用户是否要玩。
  4. 您编写的代码永远不会打“ Tie Game”,因为您正在将字符串与整数进行比较。保存在变量中的用户输入将为字符串,comp而随机输出的用户输入将为整数。您已将用户输入转换为整数int(user)
  5. 可以简单地使用in运算符检查用户输入是否有效。

码:

import random

while True:
     comp = random.choice([1,2,3])
     user = raw_input("Please enter 1, 2, or 3: ")
     if int(user) in [1,2,3]:
         if int(user) == comp:
            print("Tie game!")
         else:
            print("You lose!")
     else:
            print("Your choice is not valid.")

     play_again = raw_input("If you'd like to play again, please type 'yes'")
     if play_again == "yes":
        continue
     else:
         break
Run Code Online (Sandbox Code Playgroud)