【问题标题】:while loop repeats once when it should stopwhile 循环在应该停止时重复一次
【发布时间】:2019-07-16 03:47:05
【问题描述】:

这个 while 循环应该在 option = "e" 时停止,但是当 option = "e" 它以某种方式将 option 设置为 ""(我已经用调试器检查过)并再次运行(尽管 option = "")是在 while 循环之外,它仅在您将选项设置为“e”两次时才会停止。 Option 不是全局变量,因此函数无法更改其值。

我已经尝试使用 while True: 和一个 break 命令 when option = "e" 但它没有跳出循环

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 结束游戏:”时,我希望它能够跳出循环

【问题讨论】:

  • 您发布的代码肯定与您描述的不一样;您未发布的代码中一定还有其他内容。我们感谢您将代码简化为最小示例 - 但您需要验证它是否仍然存在问题!
  • 我知道,你是对的,我只是忘记复制下面的代码,这是导致问题的原因,谢谢

标签: python loops while-loop


【解决方案1】:

检查这是否是您所期望的。我试图重新创建上述错误,我无法重新创建它。如果你再次得到它,请告诉我。

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.")

【讨论】:

  • 您没有阅读他说实际问题出在不同代码中的评论吗?
猜你喜欢
  • 1970-01-01
  • 2014-10-02
  • 2019-01-17
  • 2013-02-02
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-09
相关资源
最近更新 更多