Determining Leap Year using Python

2023

In this project, we will discuss a Python code snippet that determines whether a year is a leap year or a common year. We'll explain each step of the code and provide the final working code at the end.


Getting User Input

To begin, we need to obtain a year from the user. We can use the input() function to prompt the user to enter a value. Let's store the user's input in a variable called a:

a = int(input("Enter a year: "))

Checking if the Year is a Leap Year

Next, we will use an if statement to check if the given year is a leap year. In the Gregorian calendar, a leap year is either divisible by 400 or divisible by 4 but not divisible by 100.

if (a % 400 == 0) or (a % 4 == 0 and a % 100 != 0):
    print("The year is a leap year.")

In this code snippet, (a % 400 == 0) checks if the year is divisible by 400. If it is, the year is a leap year. Otherwise, (a % 4 == 0 and a % 100 != 0) checks if the year is divisible by 4 but not divisible by 100. If this condition is true, the year is also a leap year.

Checking if the Year is a Common Year

To complete our code, we will add an else statement to handle the case when the year is a common year. If the year does not meet the conditions for being a leap year, it is a common year.

else:
    print("The year is a common year.")

Final Code

Here's the complete Python code that determines whether a year is a leap year or a common year:

a = int(input("Enter a year: "))

if (a % 400 == 0) or (a % 4 == 0 and a % 100 != 0):
    print("The year is a leap year.")
else:
    print("The year is a common year.")

That's it! You now have a Python code snippet that determines whether a year is a leap year or a common year. Feel free to modify the code or use it as a starting point for your own projects. Happy coding!

Back