循环错误(作业)

时间:2015-02-02 09:22:14

标签: python python-2.7

我有一个问题(显然)循环没有按预期工作。假设其他所有内容都按预期工作,我的第二个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

1 个答案:

答案 0 :(得分:1)

你的循环工作得很好;它就像你告诉它一样永远循环:

while True:

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

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

或使用break关键字明确地突破循环:

while True:
    # game
    #
    # stop playing with
    break