'I am building a clock but it keeps resetting every minute
import os
import time
count = 0
minute = 0
hour= 0
day_week = 1 #this is for the NAME of the day
day_list = [" ", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday", "Sunday"]
month_day = 1 #this is for the NUMBER of the month
month_list = [" ", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
month_count = 1
year = 0
while True:
for second in range(0,60):
command = 'clear'
if os.name in ('nt', 'dos'):
command = 'cls'
os.system(command)
print(month_list[month_day], day_list[day_week], f"{hour:02d}", ":", f"{minute:02d}", ":", f"{second:02d}")
if second == 59 :
second = 0
minute += 1
elif minute == 59 :
second = 0
minute = 0
hour += 1
elif hour == 12 and count < 2 :
second = 0
minute = 0
hour = 0
count += 1
hour += 1
elif count == 2 :
second = 0
minute = 0
hour = 0
day_week += 1
month_day += 1
count = 0
elif day_week == 7 :
second = 0
minute = 0
hour = 0
day_week = 1
month_day += 1
count = 0
elif month_day == 28 and month_count == 2 :
second = 0
minute = 0
hour = 0
month_day = 1
month_count += 1
count = 0
elif month_day == 29 and month_count == 2 and year/4 :
second = 0
minute = 0
hour = 0
month_day = 1
month_count += 1
count = 0
elif month_day == 30 and month_count == 4 or 6 :
second = 0
minute = 0
hour = 0
month_day = 1
month_count += 1
count = 0
elif month_day == 31 and month_count == 1 or 3 or 5 or 7 or 8 or 10 or 12 :
second = 0
minute = 0
hour = 0
month_day = 1
month_count += 1
count = 0
elif month_count > 12 :
second = 0
minute = 0
hour = 0
month_day = 1
month_count = 1
count = 0
time.sleep(1)
The problem seems to be coming from the part of the code between "month_day == 29" and "month_count > 12"
Solution 1:[1]
As pointed out by Michael Butscher problem is f.e. in this part of code:
elif month_day == 30 and month_count == 4 or 6 :
second = 0
minute = 0
hour = 0
month_day = 1
month_count += 1
count = 0
when you write statement like this python interprets it as
(month_day == 30 and month_count == 4) or 6
Where bool(6) = True (for every integer other than zero it returns true)
Therefore code in this if is executed in every iteretion, which you cant see because month_day is 1 as default and second is local for the scope of loop and after changing, it goes to next value in iterator and that's what you print. Also luckily minutes don't get set to zero at sec = 59 because first if statement is true therefore elifs are skiped
Adjust all expressions to sth more like:
month_day == 30 and month_count == 4 or month_count == 6
or:
month_day == 30 and (month_count == 4 or month_count == 6)
and it may work better
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | piotre10 |
