Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k 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 Reply

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...