+ 2

How to check for a year is leap year or not using if else statement

12th May 2019, 6:26 PM
Akshansh
7 Réponses
+ 4
One way is to use module calendar. import calendar print(calendar.isleap(1900)) Otherwise the rule is: A leap year is exactly divisible by 4 except for century years (years ending with 00). The century year is a leap year only if it is perfectly divisible by 400.
12th May 2019, 6:33 PM
Lothar
Lothar - avatar
+ 4
hi Michael, there is may be a misunderstanding on how a leap year is calculated. You can check this easyly by using the python function as I mentioned in my previous post. So for example the year 1900 would be leap year using only fo a division by 4, wich does not have a remainder. But it is not a leap year as it is also divisible by 100 but not by 400.
13th May 2019, 4:45 PM
Lothar
Lothar - avatar
+ 4
Hi Lothar, thanks for pointing out my mistake. At first I thought any year divisible by 4 was a leap year, but after your reply I did some research and saw that you are correct. My mistake. As for the question, we now need to include this new condition that centennial years must be divisible by 400. So we can now write this (in python): if year%100==0: # if the year is divisible by 100, thus a centennial year if year%400==0: # if the centennial year is divisible by 400 return True else: return False else: if year%4==0: return True else: return False This should now accurately test to see if a year is a leap year or not, but of course, you could always use the calendar module that Lothar stated.
13th May 2019, 10:41 PM
Michael
+ 2
A year is a leap year if it can be divided by 4 (doesn't matter if it's a century year or not like the other answer stated). If you already have your year variable defined, you could simply write something like this (in python): if year%4==0: return True else: return False The if statement checked if the year was divisible by 4 by checking if the remainder was 0. If it is, then the year is divisible by 4 and True is returned.
13th May 2019, 3:52 AM
Michael
+ 2
hi Michal, great job. It‘s perfect!!!
14th May 2019, 9:15 AM
Lothar
Lothar - avatar
+ 1
Refer to Michael's response and at last, I am able to solve the problem. Thank you Michael!
14th Mar 2021, 8:02 PM
Somnath Das
Somnath Das - avatar
+ 1
I know this is exactly like Michaels and I would like to thank him for giving me a hint for the start with the ordering. (since I don't like copying and pasting someone else's work and trying to figure it out on my own.) He helped me understand to divide the 100 and then the 400 before dividing the 4. it took me many tries and I came up we the exact same solution. year = int(input()) if year%100==0: if year%400==0: print("Leap year") else: print("Not a leap year") else: if year%4==0: print("Leap year") else: print("Not a leap year") THANK YOU MICHAEL!
5th Sep 2021, 10:39 PM
Kyle Costain
Kyle Costain - avatar