【发布时间】: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从循环内退出,return或return <exit-value/object>从函数返回,并且您可以使用return快捷方式从函数内的循环中断(只要你知道返回值是什么)。不要使用sys.exit()作为一些核霰弹枪来逃避所有控制流结构! (拆解、内存泄漏、内务管理、消息记录、GUI 线程、持久性存储......这只是为什么这是一个糟糕的习惯的众多原因中的一部分。此外,它会搞砸单元测试/测试驱动设计) -
给变量赋值然后立即返回也没有意义。你至少做了两次(
good_weather)。请改用return True和return False。 -
@ReutSharabani:其实这六行都可以换成
return (seconds <= 5)。 -
或者整个函数用
return (time.time() % 10) <= 5
标签: python while-loop