【问题标题】:Looping error (homework)循环错误(作业)
【发布时间】:2015-02-02 09:22:14
【问题描述】:

我遇到了(显然)循环无法按预期工作的问题。假设其他一切都按预期工作,我的第二个 while 循环(根据评分者)调用 raw_input 的次数超过了必要的次数。

代码玩文字游戏。您可以打一手牌、重打一手牌或退出。第二个循环决定你是玩手还是玩电脑。

所有被调用的函数都能正常工作,但是循环,正如我所说的,调用 raw_input 的次数太多了。

抱歉,如果还有很多其他问题,我对编码比较陌生。

userInput = ''
playInput = ''
hasPlayed = False

# while still playing, e exits
while userInput != 'e':

    userInput = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ").lower()

    if userInput not in 'nre':

        print("Invalid command.")

    elif userInput == 'r' and hasPlayed == False:

        print("You have not played a hand yet. Please play a new hand first!")
        print

    else:

        while True:

           # 
            print
            playInput = raw_input("Enter u to have yourself play, c to have the computer play: ").lower()

            if playInput == 'u':

                print
                hand = dealHand(HAND_SIZE)
                playHand(hand, wordList, HAND_SIZE)
                hasPlayed = True

            elif playInput == 'c':

                print
                hand = dealHand(HAND_SIZE)
                compPlayHand(hand, wordList, HAND_SIZE)
                hasPlayed = True

            else:

                print("Invalid command.")
    print

【问题讨论】:

  • 我不认为它调用raw_input as such 太多次,但它永远循环,所以你永远没有机会在'nre' a 中进行选择第二次。

标签: python python-2.7


【解决方案1】:

您的循环运行良好;它就像你告诉它的那样永远循环:

while True:

那么缺少的是一种退出该循环的方法。测试不同的条件:

playing = True
while playing:
    # game
    #
    # stop playing with
    playing = False

或使用break 关键字显式跳出循环:

while True:
    # game
    #
    # stop playing with
    break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多