Python while循环被跳过

时间:2020-08-07 09:14:54

标签: python

我正在尝试制作一个倒数时钟,当我运行它时,最后一个while循环被跳过,循环完全退出。可能是什么问题?

def countdown():
    print("Give the time for the countdown separated by a space.")
    time.sleep(0.3)
    print("If none just type in 00")
    hours_time = int(input("Hours:"))
    min_time = int(input("Minutes:"))
    sec_time = int(input("Seconds:"))
    print("Countdown will run for:{}Hr {}min {}sec".format(hours_time, min_time, sec_time))
    while (sec_time != 00):
        print("{}Hr {}min {}sec".format(hours_time, min_time, sec_time))
        time.sleep(1)
        sec_time = sec_time - 1
        while (min_time != 00 and sec_time == 00):
            print("{}Hr {}min 00sec".format(hours_time, min_time))
            time.sleep(1)
            min_time = min_time - 1
            sec_time = sec_time + 59
            while (hours_time != 00 and min_time == 00 and sec_time == 00):
                print("{}Hr 00min 00sec".format(hours_time))
                time.sleep(1)
                hours_time = hours_time - 1
                min_time = min_time + 59
                sec_time = sec_time + 59

countdown()

2 个答案:

答案 0 :(得分:1)

您只需要一个while循环。每次将秒数减少1,如果秒数降至零以下,则相应地调整分钟,并类似地调整小时数:

    while sec_time != 0 or min_time != 0 or hours_time != 0:
        print("{}Hr {}min {}sec".format(hours_time, min_time, sec_time))
        time.sleep(1)
        sec_time -= 1
        if sec_time < 0:
            sec_time += 60
            min_time -= 1
            if min_time < 0:
                min_time += 60
                hours_time -= 1

答案 1 :(得分:1)

这使用格式字符串使您的时间值具有前导零:

seconds = (hours_time*60 + min_time)*60 + sec_time
while seconds != 0:
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    print("{0:02d}Hr {1:02d}min {2:02d}sec".format(h,m,s))
    time.sleep(1)
    seconds = seconds - 1
相关问题