Welcome back to the 150 Days of Python series! π―
Today, we’re solving a real-world logic problem — checking whether a year is a leap year.
This is a great exercise to understand:
- Conditional statements
- Logical operators (and, or)
- Writing clean, readable code
Problem Statement
Write a Python program to check whether a given year is a Leap Year or Not.
Understanding Leap Year Logic
Before coding, let’s understand the rules:
A year is a leap year if:
✔ Divisible by 4
❌ But NOT divisible by 100
✔ EXCEPTION: If divisible by 400, then it is a leap year
Year Result
2024 ✅ Leap Year
1900 ❌ Not Leap Year
2000 ✅ Leap Year
Method 1 – Using if-elif-else
year = 2024 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print("Leap Year") else: print("Not a Leap Year")
Code Explanation:
- year % 4 == 0
π Checks if year is divisible by 4 - year % 100 != 0
π Ensures it is NOT divisible by 100 - year % 400 == 0
π Special case: makes century years valid - and → both conditions must be true
- or → at least one condition must be true
π This full condition ensures accurate leap year calculation
Method 2 – Taking User Input
π What’s new here?
- input() → takes user input
- int() → converts string input into integer
π Always convert input when dealing with numbers!
Method 3 – Using a Function
π Why use a function?
- Code becomes reusable
- Cleaner structure
- Easy to test
π You can call this function anytime with different values
Method 4 – Using Python calendar Module
π Explanation:
- calendar.isleap(year)
π Built-in Python function
π Returns True or False
π This is the simplest and most reliable method
Important Things to Remember
✔ Always use correct logical condition
✔ Don’t forget parentheses ( ) in conditions
✔ Convert input using int()
✔ Built-in functions save time and reduce errors
Summary
| Method | Concept |
|---|---|
| if-else | Basic logic |
| User Input | Real-world usage |
| Function | Reusability |
| calendar module | Pythonic approach |


0 Comments:
Post a Comment