在 Pyhton 中结束 while 循环

问题描述 投票:0回答:2

我正在尝试用 Python 编写剪刀布石头,但我无法为用户提供停止/打破循环的选项。我才刚刚开始,我很困惑!

def play1():
        tally = 0
        for turn in range (1 , 4) :
                computer = random.choice ( ['Scissors', 'Paper', 'Rock'])
        #user input 
                user = input("Enter guess " + str(turn) + (":"))
        #process
                if computer == user :
                        print ("Its a draw!")
                        print ("the computers choice was" , computer)
        #process
                elif(computer == 'Rock' and user == 'Scissors') or \
                     (computer == 'Scissors' and user == 'Paper') or \
                     (computer == 'Paper' and user == 'Rock') :
                        print ("you lost against the computer!")
                        print ("The computers choice was...: ", computer)

                        
        
                else :
                        print ("You win!")
                        print ("the computers choice was" , computer)
                        tally = tally + 1
                

                        
                               
        #output
                
        print ("the overally tally is......" + str(tally) + "/3!")

        if (tally == 1) :
                print ("youve lost overall...")

        if (tally >= 2) :
                print ("you've won overall!")

while True:
    answer = input("would you like to play?: ")
    if answer == 'yes':
            print ("choice registerd.")
            print ("would you like to know the rules of the game?")
            user = input (":")
            if user == 'no':
                    play1()
            if user == 'yes' :
                    print ("this is normal scissors paper rock")
                    print ("Scissors beats paper, paper beats rock, and rock")
                    print ("beats scissors")
                    play1()
      

我尝试使用“break”并继续,但我认为我显然这样做是错误的,只是将它们放在了错误的位置。

python while-loop break
2个回答
0
投票

在 while 循环中,当您从用户获取输入时,我会执行如下操作

while True:
   answer = input("would you like to play?: ")
   if answer == "yes":
      # The code you wrote
   elif answer == "no":
      break

仅供参考:

break表示你想完全退出循环等
继续表示您要跳到循环的下一次迭代


0
投票

您应该使用变量

while True:
,而不是
while isPlaying:
然后,在 while 循环结束时询问“再次播放”,并将 True/False 保存在
isPlaying
变量中。

© www.soinside.com 2019 - 2024. All rights reserved.