python怎么算闰年
时间: 2023-11-11 17:05:17 浏览: 41
要判断一个年份是否是闰年,可以使用以下逻辑:
1. 如果年份能被4整除,但不能被100整除,那么它是闰年。
2. 如果年份能被400整除,那么它也是闰年。
你可以使用以下 Python 代码来判断一个年份是否是闰年:
```python
def is_leap_year(year):
if year % 4 == 0 and year % 100 != 0:
return True
if year % 400 == 0:
return True
return False
# 测试一些例子
print(is_leap_year(2000)) # True
print(is_leap_year(2020)) # True
print(is_leap_year(1900)) # False
print(is_leap_year(2021)) # False
```
这段代码定义了一个 `is_leap_year` 函数,接受一个年份作为参数,并返回一个布尔值表示该年份是否是闰年。将你想要判断的年份传递给该函数,并打印结果即可。
相关问题
python123闰年判断
以下是两种Python判断闰年的例子:
1.使用函数判断闰年
```python
def is_leap_year(year):
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
return True
else:
return False
year = 123
if is_leap_year(year):
print("%d是闰年" % year)
else:
print("%d不是闰年" % year)
```
2.使用循环判断闰年
```python
while True:
year = input("请输入判断的年份:")
if int(year) < 0:
print("年份不能为负")
break
if int(year) % 100 == 0:
if int(year) % 400 == 0:
print("%d是闰年" % int(year))
else:
print("%d不是闰年" % int(year))
else:
if int(year) % 4 == 0:
print("%d是闰年" % int(year))
else:
print("%d不是闰年" % int(year))
```
python输出闰年
在Python中,可以使用以下代码判断一个年份是否为闰年:
```
year = int(input("请输入一个年份:"))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print(year, "是闰年")
else:
print(year, "不是闰年")
```
要输出指定范围内的闰年,可以使用以下代码:
```
start = int(input('输入开始年份:'))
end = int(input('输入结束年份:'))
print('%d年到%d年的闰年有:' % (start, end))
count = 0
for i in range(start, end + 1):
if i % 4 == 0 and i % 100 != 0 or i % 400 == 0:
print('%d年' % i, end=" ")
count += 1
if count % 5 == 0:
print()
```
请注意,以上代码中的 `input()` 函数用于获取用户输入的数据,返回值为字符串类型,需要使用 `int()` 函数将其转换为整数类型。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)