To check if a year is a leap year in Python, 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
# Test the function
print(is_leap_year(2000)) # True
print(is_leap_year(2004)) # True
print(is_leap_year(2100)) # False
print(is_leap_year(2012)) # True
print(is_leap_year(1900)) # False
This program defines a function called is_leap_year()
that takes in a year as a parameter and returns a Boolean value indicating whether or not the year is a leap year. A leap year is a year that is divisible by 4, unless it is also divisible by 100. However, if a year is divisible by 400, it is still considered a leap year.
The function first checks if the year is divisible by 4 using the modulo operator (%
). If it is, it checks if the year is divisible by 100. If it is, it then checks if the year is divisible by 400. If any of these conditions are met, the function returns, indicating that the year is a leap year. If none of the conditions are met, the function returns False
.
The program then tests the function by calling it several different years and printing the result. For example, when the function is called with the year 2000 as an argument, it returns True
because 2000 is divisible by 4, 100, and 400. Similarly, when the function is called with the year 2004 as an argument, it returns True
because 2004 is divisible by 4 but not by 100 or 400. On the other hand, when the function is called with the year 2100 as an argument, it returns False
because 2100 is divisible by 4 and 100, but not by 400.
- pybase64 encode and decode Messages using Python - June 6, 2023
- Different Data Types in Dart - June 6, 2023
- What is flutter and dart and the difference - June 4, 2023