首页 > 解决方案 > 为什么我的嵌套while循环不起作用python?

问题描述

所以我正在制作一个摇滚纸游戏,我已经添加了我的源代码。到目前为止,我已经让玩家输入他们的选择。我尝试添加检查以确保他们输入的选项是三个选项之一。我的程序纠正了一次,然后它停止做任何事情

这就是发生的事情,它会一直这样,直到我强制退出

这是我的源代码。

print('''Please pick one of the following:
Rock
Paper
Scissors''')
p1 = None
p2 = None
while True:
    gameDict = {"rock":1,"paper":2,"scissors":3}
    in1 = input("Player 1: ").lower()
    in2 = input("Player 2: ").lower()
    p1 = gameDict.get(in1)
    p2 =gameDict.get(in2)
    while gameDict.get(p1)==None or gameDict.get(p2)==None:
        if(p1==None):
            p1=input("Player 1, please enter one of the choices listed above: ")
        elif p2== None:
            p2=input("Player 2, please enter one of the choices listed above: ")
    print('Done!!')
    print(p1,p2)

标签: python

解决方案


并不是它什么都没做。事实上它做了很多,它处于一个无限循环中。输入错误时会发生什么:

  • p1 = None, p2 = None.
  • 在第一次迭代中,由于p1 == None计算结果为true,它执行if语句,分配一个新值p1,现在它不再存在None了。
  • 在第二次迭代中,p2 == None计算结果为true,它执行if语句,分配一个新值p2,现在它不再存在None了。
  • 之后,两者p1p2都不是None,因此没有任何if语句被执行并且循环无限迭代。

我建议您执行以下操作:

print('''Please pick one of the following:
Rock
Paper
Scissors''')
p1 = None
p2 = None

while True:
    gameDict = {"rock":1, "paper":2, "scissors":3}
    in1 = input("Player 1: ").lower()
    in2 = input("Player 2: ").lower()
    p1 = gameDict.get(in1)
    p2 = gameDict.get(in2)

    while p1 ==None or p2 ==None:
        if(p1 == None):
          val = input("Player 1, please enter one of the choices listed above: ")
          if(gameDict.get(val) != None):
            p1 = val

        if p2 == None:
          val = input("Player 2, please enter one of the choices listed above: ")
          if(gameDict.get(val) != None):
            p2 = val

    print('Done!!')
    print(p1, p2)

我已经修复的东西:

  1. 为输入字符串值制作了一个专用变量,即val.
  2. 更改elif为,if因为任何一个玩家的输入都可以是有效的,但不是另一个,你会想要循环直到两者都有效。

推荐阅读