在Python中,可以使用以下几种方法来判断一个年份是否为闰年:
基本判断条件
年份能被4整除但不能被100整除,或者能被400整除。
代码实现
使用`input()`函数获取用户输入的年份,然后通过计算判断该年份是否为闰年,并输出结果。
示例1
```python
year = int(input("请输入年份:"))
if year % 4 == 0 and year % 100 != 0:
print("这是闰年")
elif year % 400 == 0:
print("这是世纪闰年")
else:
print("这是平年")
示例2
```python
while True:
year = int(input("请输入年份,判断平闰年(按空格退出):"))
if year % 4 == 0 and year % 100 != 0:
print("这是闰年")
elif year % 400 == 0:
print("这是世纪闰年")
else:
print("这是平年")
user_input = input("按空格退出")
if user_input == " ":
break
示例3
```python
def is_leap_year(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False
year = int(input("请输入一个年份:"))
if is_leap_year(year):
print(year, "是闰年")
else:
print(year, "不是闰年")
示例4
```python
def runnian(i):
return i % 4 == 0 and i % 100 != 0 or i % 400 == 0
year = int(input("输入一个年份:"))
if runnian(year):
print(year, "是闰年")
else:
print(year, "不是闰年")
示例5
```python
import calendar
year = int(input("请输入一个年份:"))
if calendar.isleap(year):
print(year, "是闰年")
else:
print(year, "不是闰年")
这些代码示例都可以有效地判断一个年份是否为闰年,并根据判断结果输出相应的信息。你可以选择其中任何一个方法来实现你的需求。