“While”条件不满足

2024-06-25 07:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在理解代码中的“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循环的第一个条件永远不会满足,循环仅在第二个条件下结束。 有人能帮我吗


Tags: theyoureadtimesleepstartnowend
1条回答
网友
1楼 · 发布于 2024-06-25 07:20:08

从您的代码中可以明显看出,您在(x或y)中的这些条件之间使用了“或”。 因此循环将继续执行,直到这两个条件都等于假值

EX:考虑循环

       `while( x || y) 
        {
             //Do something
        }`

在这里,只要x或y中的任何一个继续运行,循环就会继续运行 返回true,退出条件为x&;y返回false。(注意:x和y为 假设为伪代码中的两个不同条件)

您说过:“while循环的第一个条件永远不会满足,循环只在第二个条件下结束”。由此我推断,第一个条件('time\u now.hour<;=time\u end')始终为false,只有当第二个条件('time\u now.hour<;time\u sleep')也变为false时,控制流才会退出循环

可能的解决方案

  1. 您将“time\u end”计算为“time\u start.hour+duration”。因此,在这里您可能需要检查变量“duration”是否实际持有正确的/预期的值,查看在计算“duration”时是否遇到任何错误

  2. 如果希望在任何一个条件为false时停止循环,则必须使用“and”运算符而不是“or”

    EX:考虑循环

       `while( x && y)
        {
             //Do something
        }`
    

    在这里,只要x和y继续返回,循环将继续运行 如果为true,则退出条件为其中任何一个返回false 假设为伪代码中的两个不同条件)

  3. 您应确保循环条件中的变量按照预期的循环逻辑进行更新,确定循环条件的变量动态计算中的任何错误都将产生错误的结果,例如,在您的代码中,第一个条件的循环变量是“time_now.hour”和“time_end”,因此请确保使用循环的预期值更新它们(计算中可能存在任何逻辑错误)

我认为您的问题将在上面给出的解决方案1上得到解决

相关问题 更多 >