python判断闰年?用户输入年份 判断是否为闰年
时间: 2023-11-28 12:04:57 浏览: 177
可以使用以下代码来判断用户输入的年份是否为闰年:
```python
year = int(input("请输入一个年份:"))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "是闰年")
else:
print(year, "不是闰年")
```
代码解释:
- 用户通过 `input()` 函数输入一个年份,使用 `int()` 函数将输入的字符串转换为整数类型。
- 使用条件语句 `if` 和 `else` 判断该年份是否为闰年。闰年的判断条件为:能被4整除但不能被100整除,或者能被400整除。
- 如果年份符合闰年的条件,输出“是闰年”;否则输出“不是闰年”。
相关问题
python中判断用户输入的年份是否为闰年
判断闰年的代码可以写成:
```
year = int(input("请输入一个年份:"))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print(year, "是闰年")
else:
print(year, "不是闰年")
```
注意,闰年的定义是:能被4整除但不能被100整除,或能被400整除。
输入年份,判断是不是闰年?
判断一个年份是否为闰年有以下规则:
1. 如果这个年份能被4整除,但不能被100整除,那么这一年就是闰年。
2. 如果这个年份能被400整除,那么这一年也是闰年。
因此,可以编写以下 Python 代码来判断一个年份是否为闰年:
```python
def is_leap_year(year):
if year % 4 == 0 and year % 100 != 0:
return True
elif year % 400 == 0:
return True
else:
return False
```
其中,is_leap_year 函数接受一个年份作为参数,如果这个年份是闰年,则返回 True,否则返回 False。