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

Python 如何询问用户是否希望再次播放并重复while循环?,python,loops,while-loop,nested,Python,Loops,While Loop,Nested,在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

在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.")
所以这部分是有效的。但是,我如何退出这个循环,因为在输入正确的输入后,它会不断询问“请输入1,2,3”

我还想问一下球员是否想再次比赛:

Psuedocode:

     play_again = input("If you'd like to play again, please type 'yes'")
     if play_again == "yes"
         start loop again
     else:
         exit program
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
这是否与嵌套循环有关?

为您的代码指出:

  • 粘贴的代码在if、elif和else之后没有:'
  • 可以使用控制流语句(如
    continue和break
    )实现您想要的任何功能
  • 您需要从“YouLose”中删除break,因为您想询问用户是否想玩
  • 您编写的代码将永远不会出现“平局”,因为您正在比较字符串和整数。保存在变量中的用户输入将是字符串,随机输出的
    comp
    将是整数。您已将用户输入转换为整数,即
    int(user)
  • 检查用户输入是否有效,只需使用操作符中的
    进行检查即可
  • 代码:

         play_again = input("If you'd like to play again, please type 'yes'")
         if play_again == "yes"
             start loop again
         else:
             exit program
    
    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
    

    “正确输入”是什么意思?您的程序最多允许“平局游戏!”。这是在输入正确的输入后进行的吗?你想在那之后打破循环吗?如果是,那么你可以很容易地遵循“你输了!”案例的相同模式…@Lizzie-请检查更新的代码和注释