Implement the basic algorithm in Python to deepen your understanding of the algorithm. Leap year is treated as the sixth bullet.
Conditions
A year divisible by 4 is called a leap year.
In this way, if even the caution (*) of the condition is not satisfied, a leap year is simply divisible by 4. I implemented this in python. The code and output are shown below.
leap_year.py
"""
2020/12/18
@Yuya Shimizu
leap year
・ Year divisible by 4
However, a year that is divisible by 100 and not divisible by 400 is not a leap year.
"""
def leap_year(year):
if year%100 == 0 and year%400 != 0:
print(str(year) + "The year is not a leap year.")
else:
if year%4 == 0:
print(str(year) + "The year is a leap year.")
else:
print(str(year) + "The year is not a leap year.")
year = int(input("Leap year judgment\n>>"))
leap_year(year)
Leap year judgment
>>2000
2000 is a leap year.
Leap year judgment
>>1900
1900 is not a leap year.
Judgment was made by user input. The code is pretty simple, and the caveat is that it brings in more specific conditions first.
The above program was reorganized with reference to the comments from @shiracamus. Specifically, print in the function is omitted and True and False are returned. The code and output are shown below.
leap_year_.py
"""
2020/12/18
@Yuya Shimizu
leap year
・ Year divisible by 4
However, a year that is divisible by 100 and not divisible by 400 is not a leap year.
Reorganized version
@True, referring to the proposal of shiracamus,Made a program that returns False
"""
def leap_year(year):
if year%100 == 0 and year%400 != 0:
return False
else:
if year%4 == 0:
return True
else:
return False
year = int(input("Leap year judgment\n>>"))
print(leap_year(year))
Leap year judgment
>>2020
True
I made a better one.
I've written leap year code a couple of times before, but I think it's relatively simple, probably because I was able to sort out my mind a little through the algorithm.
Introduction to algorithms starting with Python: Standards and computational complexity learned with traditional algorithms Written by Toshikatsu Masui, Shoeisha
Recommended Posts