Today, I just got back to python after a few months. So when coming back, I got an assignment. My assignment was to check if a year is a leap year. In the assignment, it also gave hints. These were the hints:
-
A leap year is a calendar year that contains an additional day (February 29th) compared to a common year. It occurs once every four year. s This is how you can determine if a year is a leap year or not:
-
if (year is not divisible by 4) then (it is a common year).
-
else if (year is not divisible by 100) then (it is a leap year)
-
else if (year is not divisible by 400) then (it is a common year)
-
else (it is a leap year)
Below the bolded words are the main hints. It basically told us how to do it. Can you see it?
If not, what it is trying to say is that we will have to use the if statement. Below, I have typed out how to do it, also using the comments to explain simply what each part of the code is doing. (Basically the words next to the ‘hashtag.’)
#This will bring in current datetime
import datetime
# Ask the user to 'enter a year'
year_input = input("Enter a year: ")
year = int(year_input)
is_leap_year = False
# if (year is not divisible by 4) then (it is a common year).
if year % 4 != 0:
is_leap_year = False
# else if (year is not divisible by 100) then (it is a leap year)
elif year % 100 != 0:
is_leap_year = True
# else if (year is not divisible by 400) then (it is a common year)
elif year % 400 != 0:
is_leap_year = False
else:
is_leap_year = True
# Set the tense to be as 'is', 'was', or 'will be' depending on
# the given year
to_be = 'is' # default
#1. find the current year
today = datetime.date.today()
current_year = today.year
#2. Compare with the input year and current year
if current_year > year:
to_be = 'was'
elif current_year < year:
to_be = 'will'
else:
to_be = 'is'
# create friendly output for printing out
if is_leap_year:
if year > current_year:
leap_year_output = "will be"
else:
leap_year_output = f"{to_be}"
else:
# future input
if current_year < year:
leap_year_output = "will not be"
else:
leap_year_output = f"{to_be} not"
#The sentence it'll print out back to the user.
print(f"The year {year} {leap_year_output} a leap year.")
And there you have it! See ya next time! :>