0.任务描述
用列表替换上一次程序的元组;
并且将判断闰年函数化
1.元组与列表
- 元组与列表的元素访问方式是一样的;
- 元组的元素在创建完成后,不支持增删改;而列表支持增删改查;
- 列表和元组同属于序列,二者元素均存在顺序前后关系;
2.程序与结果
"""
判断输入日期为当前年份的第几天
用列表代替元组
"""
from datetime import datetime
def is_leap_year(year):
return (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0)
def cal_which_day(date_str):
input_date = datetime.strptime(date_str, "%Y/%m/%d")
year = input_date.year
month = input_date.month
day = input_date.day
# month_days_tuple = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
# 用列表代替元组
month_days_list = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap_year(year): # 如果是闰年,将2月对应改成29天
month_days_list[1] = 29 # 之前元组没有这样做,是因为元组不支持修改元素
total_month_days = sum(month_days_list[:month - 1]) # 并且这样处理之后,不需要对total_days进行+1
total_days = total_month_days + day
return total_days
def main():
input_date_str = input("请输入日期(yyyy/mm/dd):")
which_day = cal_which_day(input_date_str)
print("{}是当年的第{}天~".format(input_date_str, which_day))
if __name__ == '__main__':
main()
Y:\Python\Anaconda\python.exe Y:/PythonWorkspace/lect06/WhichDay2.py
请输入日期(yyyy/mm/dd):2019/04/27
2019/04/27是当年的第117天~(列表取代元组)
Process finished with exit code 0
Y:\Python\Anaconda\python.exe Y:/PythonWorkspace/lect06/WhichDay2.py
请输入日期(yyyy/mm/dd):2008/04/27
2008/04/27是当年的第118天~(列表取代元组)
Process finished with exit code 0