Python嵌套'while'循环没有正确执行

时间:2015-07-25 21:41:34

标签: python while-loop

我是Python的新手。我想出了一个简单的程序来测试我学到的一些工具。除了我的一个嵌套'while'循环之外,它大部分都有效。以下是我的代码。不起作用的部分是当我在我的工作功能中输入“手动”并且它正在“下雨”时。我打算用它来打印rainedOut然后再回到raw_input。只有一次下雨3次(即循环回到raw_input 3次并且下雨后),它应该打印出“你现在应该放弃它”。并退出该功能。然而,它的作用是,它首先打印出rainedOut连续3次,然后自动结束该功能。任何人都可以帮我解决代码中的错误吗?

import time
import sys

done = "I'm tired of you. Goodbye."
rainedOut = "Sorry, rain foiled your plans :("
dontUnderstand = "I'm sorry, I don't understand."

def good_weather():
    """Imagine a world where every 5 seconds it rains (good_weather = False),
    then is sunny again (good_weather = True). This function should return
    whether good_weather is True or False at the time it's called.
    """
    seconds = time.time()
    seconds %= 10

    if seconds <= 5:
        good_weather = True
        return good_weather
    else:
        good_weather = False
        return good_weather

def start():
    entries = 0

    while entries < 4:
        choice = raw_input("Hello! What do you want to do right now? Options: 1) Sleep, 2) Work, 3) Enjoy the great outdoors: ")

        if choice == "1":
            print "We are such stuff as dreams are made on, and our little life is rounded with a sleep. - Shakespeare, The Tempest"
        elif choice == "2":
            work()
        elif choice == "3":
            outdoors()
        else:
            print dontUnderstand
            entries += 1
    print done

def work():
    entries = 0
    entries2 = 0

    while entries < 4:
        choice = raw_input("Would you prefer sedentary office work or manual labor in the elements?: ")

        if "office" in choice:
            print "The brain is a wonderful organ; it starts working the moment you get up in the morning and does not stop until you get into the office. -Robert Frost"
        elif "manual" in choice:
            sunny = good_weather()
            if sunny == True:
                print "A hand that's dirty with honest labor is fit to shake with any neighbor. -Proverb"
            else:
                while entries2 < 3:
                    print rainedOut
                entries2 += 1
                print "You should probably just give up now."
                sys.exit()
        else:
            print dontUnderstand
            entries += 1
    print done
    sys.exit()

def outdoors():
    sunny = good_weather()
    if sunny == True:
        print "Adopt the pose of nature; her secret is patience. -Ralph Waldo Emerson"
        sys.exit()
    else:
        print rainedOut
        start() # go back to start

start()

1 个答案:

答案 0 :(得分:2)

我想你想要这个部分:

else:
    while entries2 < 3:
        print rainedOut
    entries2 += 1
    print "You should probably just give up now."
    sys.exit()

更像这样:

if entries2 < 3:
    print rainedOut
    entries2 += 1
    continue # restart loop (optional)
else:
    print "You should probably just give up now."
    sys.exit()

您会混淆while(循环)和if(测试)功能。