【问题标题】:Python nested 'while' loop not executing properlyPython 嵌套的“while”循环未正确执行
【发布时间】:2015-07-25 21:41:34
【问题描述】:

我是 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()

【问题讨论】:

  • 切勿使用sys.exit() 退出循环或函数。只是return 来自函数。至于为什么不应该,请在此处查看许多问题。如果这需要您将函数扩充到return True/False 状态,或者一些更复杂的对象/无,那么就扩充它。
  • 您应该使用break 从循环内退出,returnreturn &lt;exit-value/object&gt; 从函数返回,并且您可以使用return 快捷方式从函数内的循环中断(只要你知道返回值是什么)。不要使用sys.exit() 作为一些核霰弹枪来逃避所有控制流结构! (拆解、内存泄漏、内务管理、消息记录、GUI 线程、持久性存储......这只是为什么这是一个糟糕的习惯的众多原因中的一部分。此外,它会搞砸单元测试/测试驱动设计)
  • 给变量赋值然后立即返回也没有意义。你至少做了两次(good_weather)。请改用return Truereturn False
  • @ReutSharabani:其实这六行都可以换成return (seconds &lt;= 5)
  • 或者整个函数用return (time.time() % 10) &lt;= 5

标签: python while-loop


【解决方案1】:

我想你想要这部分:

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(测试)功能。

【讨论】:

  • 您应该向 OP 指出整个 if...elif...else 阶梯存在于 while 循环中。增加/更新循环变量的责任应该减少到该循环中的一个(或很少)点。 OP 随意使用 sys.exit() 来打破循环/从函数返回是一种糟糕的编码习惯,他们需要立即停止。
  • 虽然我非常同意,但这更多的是用于“代码审查”而不是“堆栈溢出”。我专注于他的问题。代码中存在更多问题。我们可以在问题的 cmets 中讨论它们。
  • 有效!你是对的;谢谢你。我很困惑,因为我之前试图在 work() 函数中复制类似的功能(即,当条目
  • 如果有任何关于代码的 cmets 否则 - 例如,做什么而不是 sys.extit() - 我全都听好了。我也是 SO 新手,所以我不确定这是否合适?
  • @mmrtre18:见上面我的 cmets,也在这里和 CodeReview.stackexchange.com 阅读好的代码示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多