python每日一题_Python:每日一题004

题目:

输入某年某月某日,判断这一天是这一年的第几天?

程序分析:

以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天

个人的思路及代码:

month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 ]

while True:

year = input("请输入年份:").strip()

month = input("请输入月:").strip()

day = input("请输入天:").strip()

if not year.isdigit() or not month.isdigit() or not day.isdigit():

print("您的输入有误请重新输入!")

continue

else:

year = int(year)

month = int(month)

day = int(day)

if month > 12 or day > 31 or day < 0:

print("您的输入有误请重新输入!")

continue

if (year % 4 == 0 and year %100 != 0) or year % 400 == 0:

if month > 2:

index_day = sum(month_days[:month-1]) + day + 1

else:

index_day = sum(month_days[:month-1]) + day

else:

index_day = sum(month_days[:month-1]) + day

print("这一天是一年中的第%s天" % index_day)

分析:这里考虑了大部分输入异常的情况,但是还是有输入错误但是不能检测出来的情况,比如输入4月31日不能检测出日期不正确。

再次修改增加判断条件,检测大小月和2月的问题

month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 ]

while True:

year = input("请输入年份:").strip()

month = input("请输入月:").strip()

day = input("请输入天:").strip()

if not year.isdigit() or not month.isdigit() or not day.isdigit():

print("您的输入有误请重新输入!")

continue

else:

year = int(year)

month = int(month)

day = int(day)

if month > 12 or day > 31 or day < 0:

print("您的输入有误请重新输入!")

continue

elif month in [4,6,9,11] and day > 30 or month == 2 and day > 29:

print("您的输入有误请重新输入!")

continue

if (year % 4 == 0 and year %100 != 0) or year % 400 == 0:

if month > 2:

index_day = sum(month_days[:month-1]) + day + 1

else:

index_day = sum(month_days[:month-1]) + day

else:

if month == 2 and day > 28:

print("您的输入有误请重新输入!")

continue

index_day = sum(month_days[:month-1]) + day

print("这一天是一年中的第%s天" % index_day)

其他参考解答:

参考1

def leapyear(n):

return True if (n % 4 == 0 and n % 100 != 0) or n % 400 == 0 else False

days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 ]

year, month, day = [int(x) for x in input('input year/month/day: ').split('/')]

#直接用列表解析式获取三个数据

day2 = sum(days[:month - 1]) + day

if leapyear(year) and month > 2:

day2 += 1

print(day2)

参考2

import datetime

x=int(input("请输入年份xxxx:"))

y=int(input("请输入月份xx:"))

z=int(input("请输入日xx:"))

n1=datetime.date(x,y,z)

n2=datetime.date(x,1,1)

n3=n1-n2

n3=int(n3.days)+1

print("这是这一年的第%s天"%n3)

分析:这里用datetime模块避免了输入日期不正确的情况,如果输入不正确则直接报错。

(本文编号004,首发于2018年9月14日,修改于2018年9月15日)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值