HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Leap year calculator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
leapcalculatoryear

Problem

I'm creating a program to determine whether or not a given year is a leap year. I just wanted to get anyone's feedback on it. I am aware of the calendar module in Python. I just wanted to try it from scratch.

year=int(raw_input("Input year:"))

if (year%4==0 and year%100==0 and year%400==0)or (year%4==0 and year%100 !=0 and year%400==0)or(year%4==0 and year%100 !=0 and year%400!=0):
  print str(year)+" is a leap year"
else:
    print str(year)+" is NOT a leap year"

Solution

Logic

Consider the if condition, which I have reproduced below with different alignment for ease of viewing…

if (year%4==0 and year%100==0 and year%400==0)or \
   (year%4==0 and year%100!=0 and year%400==0)or \
   (year%4==0 and year%100!=0 and year%400!=0):
    …


It's clear that the first two lines can be collapsed due to redundancy. As for the third line, any number that is not divisible by 100 is automatically not divisible by 400 as well.

if (year%4==0 and year%400==0)or \
   (year%4==0 and year%100!=0):
    …


That can be further simplified to:

if (year%4==0 and (year%100!=0 or year%400==0)):
    …


Formatting

Please take care to follow Python formatting conventions, especially the consistent indentation by four spaces, especially since whitespace is significant in Python.

year = int(raw_input("Input year: "))

if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
    print str(year) + " is a leap year"
else:
    print str(year) + " is NOT a leap year"

Code Snippets

if (year%4==0 and year%100==0 and year%400==0)or \
   (year%4==0 and year%100!=0 and year%400==0)or \
   (year%4==0 and year%100!=0 and year%400!=0):
    …
if (year%4==0 and year%400==0)or \
   (year%4==0 and year%100!=0):
    …
if (year%4==0 and (year%100!=0 or year%400==0)):
    …
year = int(raw_input("Input year: "))

if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
    print str(year) + " is a leap year"
else:
    print str(year) + " is NOT a leap year"

Context

StackExchange Code Review Q#70887, answer score: 10

Revisions (0)

No revisions yet.