为什么我的'while p1!= ...'循环永远不会停止

时间:2018-03-06 17:08:34

标签: python python-3.x while-loop user-input

def outcome(p1, p2):
    x = ''
    if p1 == p2:
        x = 0
        return x
    elif p1 == "rock" and p2 == "scissors" or p1 == "scissors" and p2 == "paper" or p1 == "paper" and p2 == "rock":
        x = 1
        return x
    elif p2 == "rock" and p1 == "scissors" or p2 == "scissors" and p1 == "paper" or p2 == "paper" and p1 == "rock":
        x = 2
        return x

a = 0
while a == 1:
    p1 = str(input("P1 choose: "))
    while p1 != "rock" or  p1 != "paper" or p1 != "scissors":
        p1 = str(input("Please select rock/paper/scissors: "))
    p2 = str(input("P2 choose: "))
    while p2 != "rock" or  p2 != "paper" or p2 != "scissors":
        p2 = str(input("Please select rock/paper/scissors: "))
    b = outcome(p1, p2)
    if b == 1:
        print("P1 wins\n")
    elif b == 2:
        print("P2 wins\n")
    elif b == 0:
        print("Tied\n")
    pit = str(input("Another one? yes/no - "))
    if pit == "no":
        a = 0
        raise SystemExit(0)

此部分永不停止:

while p1 != "rock" or  p1 != "paper" or p1 != "scissors":
        p1 = str(input("Please select rock/paper/scissors: "))

这是一个石头剪刀游戏,当我输入正确或不正确时它不起作用并不断重复。我希望它重复,直到你写下摇滚,纸张或剪刀,当你写下其中一个时,退出while循环。

3 个答案:

答案 0 :(得分:1)

while p1 != "rock" or  p1 != "paper" or p1 != "scissors":
    p1 = str(input("Please select rock/paper/scissors: "))

它说:p可能不是rockpaperscissors。如果p等于这些单词中的任何一个,则整个谓词变为True,循环继续。在应用De Morgan transform时,您误以为or and。无法退出循环,因为没有p可以同时等同rockpaper scissors

你似乎想要的是

while True:
  word = input("Please select rock/paper/scissors: ")  # it's already a string.
  if word in ("rock", "paper", "scissors"):
    break

答案 1 :(得分:1)

你应该重写你的条件:

while not (p1 == "rock" or p1 == "paper" or p1 == "scissors"):
    p1 = str(input("Please select rock/paper/scissors: "))

如果一个条件正确,则退出白色循环。

答案 2 :(得分:0)

其他答案都是正确的,但更为pythonic的方法是制作可接受输入的列表(或元组),然后检查响应是否在其中:

valids = ["rock", "paper", "scissors"]
while p1 not in valids:
    p1 = str(input("Please select rock / paper / scissors: "))

当您编写更复杂的程序时,这可以很好地扩展:不是简单的列表,也许您在参数上使用函数调用,并且在输入验证函数中,您对值执行任意数量的测试等。