为什么我的嵌套while循环不能在python中工作?

2024-10-03 19:32:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

This is what happens, and it just stays like this until I force exit

这是我的源代码

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)

Tags: ofthenoneinputget源代码选项one
3条回答

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

  • p1 = Nonep2 = 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,因为其中一个玩家的输入可能有效,但另一个玩家的输入无效,并且您希望循环,直到两者都有效

我认为这是正确的代码: (您应该检查p1或p2是否为None)

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):
            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)

您可以将用户(“剪刀”)输入的与字典中的进行比较。您需要确保钥匙是正确的:

while in1 not in gameDict:
    in1 = input("Player 1, please...: ").lower()
while in2 not in gameDict:
    in2 = input("Player 2, please...: ").lower()

获得有效输入后,您可以查找它们:

p1 = gameDict[in1]
p2 = gameDict[in2]

相关问题 更多 >