Python Function to Check Leap Years
To define a function that checks for leap years, you can use the following code:
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
year = int(input("请输入一个年份:"))
if is_leap_year(year):
print(year, "是闰年")
else:
print(year, "不是闰年")
In this code, we have defined a function called is_leap_year, which takes a year as a parameter. The logic in the function is that if the year is divisible by 4, then it checks if it is also divisible by 100. If it is, then it further checks if it is divisible by 400. If the year is divisible by 4 but not by 100, or if it is divisible by 400, then it returns True, indicating it is a leap year. Otherwise, it returns False, indicating it is not a leap year.
Finally, you can determine whether a year is a leap year by calling this function and passing in a year. If it is a leap year, print the year followed by “is a leap year”; otherwise print the year followed by “is not a leap year”.