While和if循环无法正常工作

时间:2019-07-10 20:13:34

标签: python python-3.x

我不知道为什么,但是我一直保持代码在输入部分之后直接结束。

我尝试使用elif,但语法无效。

import getpass 

answer1 = getpass.getpass(prompt = "Hello Player 1, Please pick either     ROCK (1)    SCISSORS (2)   OR   PAPER (3) \n")  

answer2 = input(("Hello Player 2, Please pick either     ROCK (1)    SCISSORS (2)   OR   PAPER (3) \n")) 

Forever = 0
while Forever < 1:  
   if answer1 == 1 and answer2 == 1:  
      print('DRAW PLAY AGAIN !')  
      Forever = Forever + 1 

   if answer1 == 2 and answer2 == 2:  
      print('DRAW PLAY AGAIN !')  
      Forever = Forever + 1 

   if answer1 == 3 and answer2 == 3:  
      print('DRAW PLAY AGAIN !')  
      Forever = Forever + 1 

   if answer1 == 1 and answer2 == 2:  
      print('Player 1 wins !') 
      Forever = Forever + 1 

   if answer1 == 3 and answer2 == 1:  
      print('Player 1 wins !')  
      Forever = Forever + 1 

   if answer1 == 2 and answer2 == 3:  
      print('Player 1 wins !')  
      Forever = Forever + 1 

   if answer1 == 2 and answer2 == 1:  
      print('Player 2 wins !')  
      Forever = Forever + 1 

   if answer1 == 1 and answer2 == 3:  
      print('Player 2 wins !')  
      Forever = Forever + 1 

   if answer1 == 3 and answer2 == 2:  
      print('Player 2 wins !')  
      Forever = Forever + 1 

代码也永远不会结束。

1 个答案:

答案 0 :(得分:0)

我不知道您为什么要用input进行一次输入,而用getpass进行一次输入,但是无论如何,您都应该将两者都更改为:

answer1 = int(getpass.getpass(...)) 
answer2 = int(input(...))

您的所有条件的格式为:answer1 == 2input的结果是一个字符串,因此所有这些检查都将失败,除非您将输入转换为整数。


我建议您也更改条件以使代码更简单。您实际上可能只有3个!最基本的建议:您可以执行以下操作,而不用打印3张不同的支票DRAW!

if answer1 == answer2:
    print('DRAW PLAY AGAIN !')

最后一点:在python中,请勿使用int来检查循环...要么while True:break when是必要的,要么仅使用Boolean变量。