題目:打印萬年歷
已知條件
閏年條件:能被4整除且不能被100整除,或者能被400整除
1900年1月1日 是周一
解題思路
判斷閏年;
判斷當月有多少天;
這個月的1號是從周幾開始的;
格式化打印日歷。
解題代碼
#判斷年份是否為閏年
def is_leap_year(year):
if (year%4==0 and year%100!=0) or (year%400==0):
return True
else:
return False
#判斷月份有多少天
def get_month_day(year,month):
days=31
if month in [4,6,9,11]:
days=30
elif month == 2:
if is_leap_year(year):
days=29
else:
days=28
return days
#求輸入年份和月份日期總天數
def get_days(year,month):
totaldays=0
for i in range(1900,year):
if is_leap_year(i):
totaldays+=366
else:
totaldays+=365
for i in range(1,month):
totaldays+=get_month_day(year,i)
return totaldays
#主程序
if __name__ == '__main__':
year = input('請輸入年份:')
month = input('請輸入月份:')
try:
year = int(year)
month = int(month)
if month < 1 or month > 12:
print('月份輸入錯誤,請重新輸入')
continue
except:
print('年份或月份輸入錯誤,請重新輸入')
continue
break
print('日\t一\t二\t三\t四\t五\t六')
count = 0
for i in range((get_days(year,month)%7)+1):
print('\t',end='')
count+=1
for i in range(1,get_month_day(year,month)+1):
print(i,end='')
print('\t',end='')
count+=1
if count%7 ==0:
print('/n')