封装一个闰年的函数,输入一个年份,判断是否为闰年
时间: 2024-05-14 15:11:58 浏览: 18
以下是Python语言的代码实现:
```
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
```
函数的参数是一个年份,函数返回值为布尔值,如果这个年份是闰年则返回True,否则返回False。
闰年的判定规则如下:
1. 能被4整除但不能被100整除的年份是闰年,如2004年就是闰年;
2. 能被4整除且能被100整除但不能被400整除的年份不是闰年,如1900年不是闰年;
3. 能被4整除且能被400整除的年份是闰年,如2000年是闰年。
相关问题
输出2010-2020年之间的闰年 函数思想:简化程序、代码复用 将判断一年是否是闰年封装为函数
以下是Python代码实现:
```python
def is_leap_year(year):
# 判断是否是闰年,是返回True,否则返回False
return year % 4 == 0 and year % 100 != 0 or year % 400 == 0
for year in range(2010, 2021):
if is_leap_year(year):
print(year)
```
输出结果为:
```
2012
2016
2020
```
解释:首先定义一个判断是否是闰年的函数is_leap_year,该函数接受一个参数year,返回一个布尔值,True表示是闰年,False表示不是闰年。然后使用一个循环遍历2010-2020年的所有年份,对于每一个年份,调用is_leap_year函数判断是否是闰年,如果是,则输出该年份。通过封装函数,可以使程序更加简洁,并且方便代码复用。
jupyter notebook封装函数求闰年
Jupyter Notebook是一个开源的交互式笔记本,它可以让你在浏览器中创建和共享文档,包括代码、方程、可视化和说明文本。它广泛用于数据分析、机器学习和科学计算等领域。
下面是一个封装函数来判断是否为闰年的例子:
```python
def is_leap_year(year):
"""
判断是否为闰年
参数:
year -- 待判断的年份
返回值:
如果是闰年,返回True;否则返回False
"""
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
```
使用该函数可以判断一个年份是否为闰年,例如:
```python
print(is_leap_year(2020)) # 输出 True
print(is_leap_year(2021)) # 输出 False
```
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)