在Python中,判断平年或闰年可以通过以下几种方法实现:
方法一:使用条件语句
```python
year = int(input("请输入年份:"))
if year % 4 == 0 and year % 100 != 0:
print("这是闰年")
elif year % 400 == 0:
print("这是世纪闰年")
else:
print("这是平年")
```
方法二:使用循环
```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
```
方法三:使用Python标准库
```python
import calendar
year = int(input("请输入年份:"))
is_leap = calendar.isleap(year)
if is_leap:
print(f"{year}年是闰年")
else:
print(f"{year}年是平年")
```
方法四:定义函数
```python
def is_leap_year(year):
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
else:
return False
year = int(input("请输入年份:"))
if is_leap_year(year):
print(f"{year}年是闰年")
else:
print(f"{year}年是平年")
```
以上方法都可以有效地判断一个年份是平年还是闰年。你可以根据自己的需求和喜好选择合适的方法。