Here is a beginner Python program, a leap year calculator, that helps determine whether a given year is a leap year or not. Since this is a beginner project, the program is focused on conditional statements: if, elif and else.
The rules for determining leap years are as follows:
If a year is divisible by 4, it is a leap year.
However, if that year is also divisible by 100, it is not a leap year, unless...
The year is also divisible by 400, in which case it is a leap year.
Now. let's convert this logic from the flowchart into code.
# Leap Year Calculator
print("Welcome to leap year calculator.\n")
# Take user input for the year
year = int(input("Type a year: \n"))
# Check if the year is divisible by 4
if year % 4 == 0:
# If the year is divisible by 100, additional check is needed
if year % 100 == 0:
# If the year is divisible by 400, it is a leap year
if year % 400 == 0:
print(f'{year} is a leap year.')
else:
print(f'{year} is not a leap year')
else:
print(f'{year} is a leap year.')
else:
print(f'{year} is not a leap year')
In summary, using nested conditionals (if and else statements in this case) is important for implementing the rules for leap years. You start with the most basic condition and progressively add more detailed checks.
*This project is part of the 100 Days of Code: The Complete Python Pro Bootcamp