top of page

Pythons Project for beginners - Post 35: Leap Year Checker

ree

Let's build a Leap Year Checker. This is a classic programming exercise that is perfect for beginners to master nested conditional logic (if/elif/else).

First, here is the explanation of how the project is built.


How the "Leap Year Checker" is Made


  1. The Core Idea: The goal is to create a program that takes a year from the user and correctly determines whether that year is a leap year based on a specific set of rules.

  2. The Rules for a Leap Year: A year is a leap year if it meets the following criteria:

    • It is evenly divisible by 4.

    • However, if the year is also evenly divisible by 100, it is not a leap year, unless...

    • ...the year is also evenly divisible by 400. Then it is a leap year. For example, 2000 and 2400 are leap years, but 1800 and 1900 are not.

  3. Getting User Input Safely: The program needs a year to check. We'll use input() to get the number from the user and int() to convert it to a whole number. This is placed inside a try...except ValueError block to ensure the program can handle cases where the user enters text instead of a valid year.

  4. The Core Logic with Nested Conditionals: The rules for a leap year translate perfectly into a set of nested ifstatements. We check the conditions in order of precedence:

    • First if: Is the year divisible by 4? (year % 4 == 0). If not, we know right away it's not a leap year.

    • Nested if: If it is divisible by 4, we then check if it's also divisible by 100 (year % 100 == 0).

    • Deepest Nested if: If it is divisible by 100, we must make one final check: is it also divisible by 400? (year % 400 == 0). Only then is it a leap year. This structure directly models the logic of the rules.

  5. Displaying the Result: Based on which condition is met, the program will print a clear message to the user, stating whether the year they entered is a leap year or not.



Comments


bottom of page