【问题标题】:Second while loop only loops once第二个while循环只循环一次
【发布时间】:2015-02-08 02:24:59
【问题描述】:

我正在制作一个石头剪刀布游戏。一切正常,除了我不明白为什么第二个 while 循环在这段代码中不起作用。我想制作这个程序,如果用户没有输入“R”或“P”或“S”,那么用户将被告知这是一个无效条目,它会提示用户再次输入他们的答案。它适用于 player1,但不适用于 player2。对于 player2,如果您没有输入“R”或“P”或“S”,那么它会提示您再次输入一个新值,但只输入一次,无论您输入什么。感谢所有帮助!

if playGame == "Y":
    print("Ok, here we go.")

    player1 = input("Player1, what is your choice, R, P, or S? ")
    player1 = player1.upper()

    while player1 != 'R' and player1 != 'P' and player1 != 'S':
            player1 = input("Invalid answer.  Please answer R, P, or S: ")
            player1 = player1.upper()

    player2 = input("Player2, what is your choice, R, P, or S? ")
    player2 = player2.upper()

    while player2 != 'R' and player2 != 'P' and player2 != 'S':
            player2 = input("Invalid answer.  Please answer R, P, or S: ")
            player2 = player1.upper()

【问题讨论】:

  • 你的代码的最后一行应该如下: player2 = player2.upper

标签: python loops while-loop


【解决方案1】:

错误在最后一行

player2 = player1.upper()

应该是

player2 = player2.upper()

【讨论】:

  • 谢谢!在查看代码时,我完全错过了这一点。我进行了更改,程序现在可以运行了。再次感谢。
  • 我还建议删除不等式检查并改用 not in。
【解决方案2】:

当用户输入无效值时,使用while循环反复询问用户。

代码:

playGame = raw_input("You want to play game: if yes then enter Y:").upper()
if playGame == "Y":
    print("Ok, here we go.")
    player1 = ''
    while  1:
        player1 = raw_input("Player1, what is your choice, R, P, or S?:").upper()
        if player1 not in ['R', 'P', 'S']:
            print "Invalid answer."
        else:
            break

    player2 = ''
    while 1:
        player2 = raw_input("Player2, what is your choice, R, P, or S?:").upper()       
        if player2 not in ['R', 'P', 'S']:
            print "Invalid answer."
        else:
            break

    print "player1:", player1
    print "player2:", player2

输出:

vivek@vivek:~/Desktop/stackoverflow$ python 7.py
You want to paly game: if yes then enter Y:Y
Ok, here we go.
Player1, what is your choice, R, P, or S?:a
Invalid answer.
Player1, what is your choice, R, P, or S?:R
Player2, what is your choice, R, P, or S?:w
Invalid answer.
Player2, what is your choice, R, P, or S?:q
Invalid answer.
Player2, what is your choice, R, P, or S?:s
player1: R
player2: S

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 2018-05-14
    • 2016-08-21
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    相关资源
    最近更新 更多