python小练习

一、判断某年的年份是否为闰年?

# function:Judging whether a year is a leap year
year = input("Please enter the year you want to judge: ")
if year.isdigit():
    year = int(year)
    if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        print(year, "is leap year!")
    else:
        print(year, "is not leap year!")
else:
    print("Please enter the correct year!")
    exit()

二、判断指定日期为该年中的第多少天?

法一:无调用第三方模块

# Calculate how many days of the year the specified time is
date = "2019-12-31"
temp = 0
year = int(date.split("-")[0])
def leapyear(y):
    return (y % 4 == 0 and y % 100 != 0 or y % 400 == 0)
month_day = [0,31,28,31,30,31,30,31,31,30,31,30]
if leapyear(year):
    month_day[2] += 1
month = int(date.split("-")[1])
day = int(date.split("-")[2])
for i in range(month):
    temp += month_day[i]
few_day = temp + day
print("%s is the %s day of %s"%(date,few_day,year))

法二:调用datetime计算

# Calculate how many days of the year the specified time is
import  datetime
year = int(input("please enter years:"))
month = int(input("please enter months:"))
day = int(input("please enter days:"))
def fewday(y,m,d):
    TargetDay = datetime.date(y,m,d)
    InitialDay = datetime.date(y,1,1)
    return (TargetDay - InitialDay).days + 1
result = fewday(year,month,day)
print("%s-%s-%s is the %s day of %s"%(year,month,day,result,year))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值