gpt4 book ai didi

Python 嵌套 'while' 循环未正确执行

转载 作者:行者123 更新时间:2023-12-01 04:36:18 26 4
gpt4 key购买 nike

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

最佳答案

我想你想要这部分:

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

关于Python 嵌套 'while' 循环未正确执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31631426/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com