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


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 winsn")
    elif b == 2:
        print("P2 winsn")
    elif b == 0:
        print("Tiedn")
    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 循环。

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

它说:p可以是任何东西,除了rockpaperscissors。如果p等于这些单词中的任何一个,则整个谓词变为True,并且循环继续。在应用德摩根变换时,您将or误认为and 。循环不能退出,因为没有p可以同时等于rockpaperscissors

你似乎想要的是

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

你应该重写你的条件:

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

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

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

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

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

相关内容

  • 没有找到相关文章

最新更新