如何使用While循环重新启动程序并继续

时间:2019-05-01 07:08:30

标签: python-3.x

我正在尝试通过While循环重新启动程序。编写完整个程序后,我将其告知“ Continue”并再次启动while循环,但它始终给我带来语法错误。有人可以解释一下我在做什么错吗?请忽略代码的质量,着重指出我的错误。谢谢!

while True:
input1 = int(input("Player one please enter your desired choice through    a number\n 1 for Rock\n 2 for Scissors\n 3 for Paper\n Enter here: "))
input2 = int(input("Player two please enter your desired choice through a number\n 1 for Rock\n 2 for Scissors\n 3 for Paper\n Enter here: "))


if input1 == input2:
    print("It's a tie")
elif input1 == 1 and input2 == 2 or input1 == 1 and input2 == 3:
    print("Player one WINS!")
elif input1 == 2 and input2 == 1:
    print("Player two WINS!")
elif input1 == 3 and input2 == 1:
    print("Player one WINS!")
elif input1 == 2 and input2 == 3:
    print("Player one WINS")
elif input1 == 3 and input2 == 2:
    print("Player two WINS!")
else:
    pass
x = int(input("Do you want to play another game?: Y/N: "))

if x == 'y':
continue
else:
break

预期结果: 程序再次运行

实际结果: SyntaxError:“继续”无法正确循环

1 个答案:

答案 0 :(得分:0)

您的x是一个int,必须将其设置为String才能比较字符串。 (使用str())

Int:

x = int(input("Do you want to play another game?: Y/N: "))

字符串:

x = str(input("Do you want to play another game?: Y/N: "))

工作版本:

  try:
      while True:
         input1 = int(input("Player one please enter your desired choice through    a number\n 1 for Rock\n 2 for Scissors\n 3 for Paper\n Enter here: "))
         input2 = int(input("Player two please enter your desired choice through a number\n 1 for Rock\n 2 for Scissors\n 3 for Paper\n Enter here: "))

         if input1 == input2:
            print("It's a tie")
         elif input1 == 1 and input2 == 2 or input1 == 1 and input2 == 3:
            print("Player one WINS!")
         elif input1 == 2 and input2 == 1:
            print("Player two WINS!")
         elif input1 == 3 and input2 == 1:
            print("Player one WINS!")
         elif input1 == 2 and input2 == 3:
            print("Player one WINS")
         elif input1 == 3 and input2 == 2:
            print("Player two WINS!")
         else:
            pass

         # x = int(input("Do you want to play another game?: Y/N: "))
         x = str(input("Do you want to play another game?: Y/N: "))
         if x == 'y':
            continue
         else:
            break

   except ValueError:
      raise ValueError('no negative numbers')
   except TypeError:
      raise TypeError('wrong type')