需求
一个很简单的控制台程序,功能主要是输入一个年份,在输入一个月份,然后程序打印出这一年这一月的阅历。该有的解释都在注释中了,可以参考下面的代码:
程序代码
MONTH_NAMES = ["Januray", "Febrary", "March", "April", "May", "Jun", "July", "August", "Septamber",
"October", "November", "December"]
START_DAY_FOR_JAN_1_1800 = 3
def main():
quit_flag= ""
while True:
quit_flag = input("请输入一个年份(例如:2020,输入q退出):")
if quit_flag == "q":
exit(0)
try:
year = int(quit_flag)
except ValueError:
print("请输入正确的数字")
continue
while not checkYear(year):
quit_flag = input("请输入一个年份(例如:2020,输入q退出):")
if quit_flag == "q":
exit(0)
try:
year = int(quit_flag)
except ValueError:
print("请输入正确的数字")
continue
quit_flag = input("请输入一个月份,输入q退出:")
if quit_flag == "q":
exit(0)
try:
month = int(quit_flag)
except ValueError:
print("请输入正确的数字")
continue
while not checkMonth(month):
quit_flag = input("请输入一个月份,输入q退出:")
if quit_flag == "q":
exit(0)
try:
month = int(quit_flag)
except ValueError:
print("请输入正确的数字")
continue
printMonth(year,month)
def printMonth(year,month):
printMonthTitle(year, month)
printMonthBody(year, month)
def printMonthTitle(year,month):
print(" " + getMonthName(month) + " "+ str(year));
print("----------------------------");
print(" Sun Mon Tue Wed Thu Fri Sat")
def getMonthName(month):
return MONTH_NAMES[month-1]
def printMonthBody(year,month):
#打印结果
startDay = getStartDay(year,month)
for i in range(startDay):
print(" ",end="")
monthDays = getNumberOfDaysInMonth(year,month)
for i in range(1,monthDays+1):
print("%4d" % i,end="")
if (i + startDay) % 7 == 0:
print()
print()
def getStartDay(year,month) -> int:
#计算这一月的第一天是周几
return ((getTotalNumberOfDays(year,month) % 7) + START_DAY_FOR_JAN_1_1800) % 7
def getTotalNumberOfDays(year,month) -> int:
#计算从1800年1月1日到[year]年[month]月一共有几天
total = 0
for i in range(1800,year):
if IsLeapYear(i):
total += 366
else:
total += 365
for i in range(1,month):
total += getNumberOfDaysInMonth(year,i);
return total
def getNumberOfDaysInMonth(year,month) -> int:
#返回这一月有几天
if month in [1,3,5,7,8,10,12]:
return 31;
if month in [4,6,9,11]:
return 30
if month == 2:
return 29 if IsLeapYear(year) else 28
def IsLeapYear(year) -> bool:
#判断闰年
return year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
def checkYear(year) -> bool:
#判断输入年份的有效性
if year < 1800:
print("该年份无效,请重新输入!")
return False
return True
def checkMonth(month) -> bool:
if(month < 1 or month > 12):
print("月份无效,请输入1-12的整数!")
return False
return True
if __name__ == '__main__':
main()
运行效果
如有错误欢迎指正