我很难理解为什么当满足条件时我的代码中的“ while”循环不会停止。
"""
:param duration: how long the loop will last in hours
:param time_pause: every x seconds the loop restarts
"""
time_start = readTime()
time_now = readTime()
time_end = time_start.hour + duration
time_sleep = conf.SETTINGS["LIGHT_UNTIL"]
print('Time when the script was started \n', time_start)
print('Script ends', time_end)
try:
while time_now.hour <= time_end or time_now.hour < time_sleep:
temp.read_temp_humidity()
lights.Lights_Time()
water.water_plants_1ch(ch_number=2, time_water=2)
time.sleep(time_pause)
time_now = readTime()
except KeyboardInterrupt:
# here you put any code you want to run before the program
# exits when you press CTRL+C
print("Keyboard interrupt \n", readTime()) # print value of counter`
readTime()函数使用此函数:
try:
ds3231 = SDL_DS3231.SDL_DS3231(1, 0x68)
print( "DS3231=\t\t%s" % ds3231.read_datetime() )
print( "DS3231 Temp=", ds3231.getTemp() )
return ds3231.read_datetime()
except: # alternative: return the system-time:
print("Raspberry Pi=\t" + time.strftime( "%Y-%m-%d %H:%M:%S" ) )
return datetime.utcnow()`
while循环的第一个条件从不满足,并且循环仅在第二个条件下结束。 有人可以帮我吗?
答案 0 :(得分:0)
从代码中可以明显看出,您在这些条件之间使用了“或”,如(x或y)。 因此,循环将继续执行,直到这两个条件都等于一个假值为止。
ex:考虑以下while循环
`while( x || y)
{
//Do something
}`
在这里,只要x或y中的任何一个继续执行,循环将继续起作用 返回true,则退出条件是x和y都返回false时(NB:x&y为 假定伪代码中有2种不同的条件)
您说:“ while循环的第一个条件永远不会满足,并且循环只会在第二个条件下结束”。由此推断,第一个条件('time_now.hour <= time_end')始终为假,并且仅当第二个条件('time_now.hour 可能的解决方案 您将“ time_end”计算为“ time_start.hour +持续时间”。因此,在这里您可能必须检查变量“ duration”是否真正持有正确/期望的值,看看在“ duration”的计算中是否遇到任何错误。 如果您希望在任何一个条件为假时停止循环,则必须使用“和”运算符而不是“或”。 ex:考虑以下while循环 这里,只要x和y继续返回,循环将继续起作用
如果为true,则退出条件是其中任何一个返回false时(NB:x&y
假定伪代码中有2个不同的条件) 您应确保根据要在循环时使用的逻辑更新循环条件中的变量,例如,确定循环条件的变量的动态计算中的任何错误都将产生错误的结果,例如在您的代码中,第一个条件的循环变量是'time_now.hour'和'time_end',因此请确保在循环时将它们更新为预期值(计算中可能存在逻辑错误)。 我认为您的问题将在上面提供的以下解决方案1上解决。
`while( x && y)
{
//Do something
}`