while循环在应停止时重复一次

时间:2019-07-15 19:08:58

标签: python loops while-loop

当option =“ e”时,此while循环应停止,但是当option =“ e”时,它将以某种方式将option设置为“”(我已经通过调试器进行了检查)并再次运行(尽管option =“”)为在while循环之外,只有将option设置为等于“ e”两次,它才会停止。选项不是全局变量,因此功能无法更改其值。

我已经尝试使用while True:和当option =“ e”时使用break命令,但不会中断循环

option = ""
hand = {0:0}
while option != "e":
    option = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
    if option == 'n':
        hand = dealHand(HAND_SIZE)
        playHand(hand,wordList,HAND_SIZE)
    elif option == 'r':
        if 0 in hand:
            print("You have not played a hand yet. Please play a new hand first!","\n")
        else:
            playHand(hand,wordList,HAND_SIZE)
    elif option != "e":
        print("Invalid command.")

当我输入“ e”(不带引号)时,如果它要求我“输入n发出新手,r重玩最后一手或e结束游戏:”,我希望它会跳出循环圈。

1 个答案:

答案 0 :(得分:0)

检查这是否是您期望的。我试图重新创建上述错误,但无法重新创建。让我知道您是否再得到它。

option = ""
hand = {0:0}
while True:
    option = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
    if option == 'n':
        hand = dealHand(HAND_SIZE)
        playHand(hand,wordList,HAND_SIZE)
    elif option == 'r':
        if 0 in hand:
            print("You have not played a hand yet. Please play a new hand first!","\n")
        else:
            playHand(hand,wordList,HAND_SIZE)
    elif option == "e":
        break
    elif option != "e":
        print("Invalid command.")