Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

python - While function stuck on first block of if-elif-else

I'm trying to code a small pomodoro-timer, it uses a while loop with an if-elif-else statement to check which timer to start.

As expected it starts with the first if-block and then modifies the variable, I would expect it to go the elif-block after that, however it seems to be stuck in the if-block. And doesn't reiterate the entire while loop code.

How to overcome this?

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

So what is wrong with this code is that you reset the last value in each repeat of the while loop, so it never persists its state for the next cycle.

You should declare the variable before the while loop to fix this issue

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...