Python Leap Year Check
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This snippet defines a small function called is_leap_year that determines whether a given year is a leap year using the standard Gregorian rules.
How the logic works:
- If the year is divisible by 4 and not divisible by 100, it is a leap year.
- If the year is divisible by 400, it is a leap year.
- Otherwise, it is not a leap year.
The function is then called as is_leap_year(1400) — the comment «محدود کردن طول کد» (shortening the code) simply explains why only a single sample call is included.
Usage: you can reuse the function anywhere date validation is required. For example is_leap_year(2024) prints “is leap year” and returns True, while is_leap_year(2023) prints “is not leap year”.
Important notes and bugs:
- The
elsebranch does not returnFalse, so the function actually returnsNonefor non-leap years. Addingreturn Falsefixes this. - Using
printinside the function makes it hard to reuse in program logic; return a boolean and let the caller decide how to display it. - The input
1400is a Jalali (Persian) year, but the algorithm is Gregorian. The result happens to be correct by coincidence (1400 is not divisible by 400). For Persian years, use a Jalali leap-year algorithm or a library such asjdatetime. - There is no input validation, so negative or non-numeric values can raise errors or give misleading answers.
Practical uses include form date validation, counting the days in a year, computing day differences between dates, and building calendars.