当函数卡在ifelifelse的第一个块上时

2024-06-08 16:39:19 发布

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

我试图编写一个小的pomodoro计时器,它使用一个while循环和if-elif-else语句来检查要启动哪个计时器

正如预期的那样,它从第一个if块开始,然后修改变量,我希望它在那之后进入elif块,但是它似乎卡在if块中。并且不会重复整个while循环代码

如何克服这个问题

import os
import time

pomodoro = ['Pomodoro', 1500]
short_break = ['Short Break', 300]
long_break = ['Long Break', 1800]
pomodori_count = 0

def countdown(time_frame):
    duration = time_frame[1]
    while duration:
        os.system('clear')

        mins, secs = divmod(duration, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)

        print(f"{time_frame[0]} | {timer}")
        time.sleep(1)
        duration -= 1

while True:
    last = ""

    if last != "Pomodoro":
        countdown(pomodoro)
        last = "Pomodoro"
        pomodori_count += 1
    elif pomodori_count % 4 != 0:
        countdown(short_break)
        last = "Short Break"
    else:
        countdown(long_break)
        last = "Long Break"

Tags: iftimecountframe计时器lastdurationcountdown
1条回答
网友
1楼 · 发布于 2024-06-08 16:39:19

因此,这段代码的错误在于,您在while循环的每个重复中重置了last值,因此它永远不会在下一个循环中保持其状态

您应该在while循环之前声明变量以解决此问题

last = ""
while True:

    if last != "Pomodoro":
        countdown(pomodoro)
        last = "Pomodoro"
        pomodori_count += 1
    elif pomodori_count % 4 != 0:
        countdown(short_break)
        last = "Short Break"
    else:
        countdown(long_break)
        last = "Long Break"

相关问题 更多 >