I'm trying to make a countdown clock and when I run it the last while loop is skipped and the loop exits completely. What could be the problem?
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()
DavidG
25.6k14 gold badges101 silver badges87 bronze badges
2 Answers 2
You only need one while loop. Decrease the seconds by 1 each time, and if it goes below zero, then adjust minutes accordingly, and similarly regarding hours:
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
answered Aug 7, 2020 at 9:26
alani
13.2k3 gold badges18 silver badges34 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
This uses format strings to make your time values have leading zeros:
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
Comments
lang-py
sec_time == 00cannot be true in the innermost loop. The containing loop already checkssec_time == 00, then doessec_time = sec_time + 59– meaningsec_timeis59before the innermost loop is entered.