我正在建造一个时钟,但它每分钟都在重置


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)

问题似乎来自于"month_day == 29"one_answers"month_count>12">

正如Michael Butscher指出的,问题是在这部分代码中:

elif month_day == 30 and month_count == 4 or 6 :
second = 0
minute = 0
hour = 0
month_day = 1
month_count += 1
count = 0

当你写这样的语句时,python将其解释为

(month_day == 30 and month_count == 4) or 6

Where bool(6) = True(对于除零以外的所有整数,它都返回True)

因此if中的代码在每次迭代中执行,你看不到,因为month_day是默认值1,second是循环作用域的局部值,在更改后,它会转到迭代器中的下一个值,这就是你打印的内容。此外,幸运的是,minutes不会在sec = 59时被设置为零因为首先if语句为真因此省略了

将所有表达式调整为:

month_day == 30 and month_count == 4 or month_count == 6

或:

month_day == 30 and (month_count == 4 or month_count == 6)

,它可能工作得更好

最新更新