第二个while循环只循环一次

时间:2015-02-08 02:25:00

标签: python loops while-loop

我正在制作一个石头剪刀游戏。一切正常,除了我无法理解为什么第二个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()

2 个答案:

答案 0 :(得分:5)

错误在最后一行

player2 = player1.upper()

应该是

player2 = player2.upper()

答案 1 :(得分:0)

当用户输入无效值时,使用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