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

Printing future leap years

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

Problem

My code prints the next 20 leap years:

def loop_year(year):
    x = 0
    while x < 20:
        if year % 4 != 0 and year % 400 != 0:
            year +=1
            ##print("%s is a common year") %(year)
        elif year % 100 != 0:
            year +=1
            print("%s is a leap year") % (year)
            x += 1

loop_year(2020)


I want to use fewer lines. I thought of using a for but some people said it was a waste of time. What else can I do?

Solution

I can't see a way to make this shorter (I can't see how is this relevant to any performance issue in Python) as your solution is straight forward but I have some advice:

Use calendar module to get rid of those ugly conditions.

calendar.isleap(year)

Formatting:

Try formatting your strings using format() (it's much cleaner looking):

This:

print("%s is a leap year") % (year)


Would become this:

print('{} is a leap year!'.format(year))


In your method, add another parameter which will be the number of years (this will make your code more user-friendly) - you don't want somebody to modify the number of leap years inside your block code. Just make it happen when they are calling the method:

def loop_year(year, number_of_years):
    ...


More, your variable names should have specific names based on their usage: I would personally change x to leap_year_counter. When it comes to a simple counter, your naming solution it's also ok, but if your code will become more robust, you'll have a hard time figuring what is what.

IF/ELSE Statements:

As others mentioned, you have year += 1 in your both statements, so just move it after them. More, in this case, you can also remove the else statement.

# ...
if calendar.isleap(year):
    print('{} is a leap year!'.format(year))
    leap_year_counter += 1
year += 1
# ...


Finally, your method will look like this:

import calendar

def loop_year(year, number_of_years):
    leap_year_counter = 0
    while leap_year_counter < number_of_years:
        if calendar.isleap(year):
            print('{} is a leap year!'.format(year))
            leap_year_counter += 1
        year += 1
loop_year(2016, 20)

Code Snippets

print("%s is a leap year") % (year)
print('{} is a leap year!'.format(year))
def loop_year(year, number_of_years):
    ...
# ...
if calendar.isleap(year):
    print('{} is a leap year!'.format(year))
    leap_year_counter += 1
year += 1
# ...
import calendar


def loop_year(year, number_of_years):
    leap_year_counter = 0
    while leap_year_counter < number_of_years:
        if calendar.isleap(year):
            print('{} is a leap year!'.format(year))
            leap_year_counter += 1
        year += 1
loop_year(2016, 20)

Context

StackExchange Code Review Q#125545, answer score: 11

Revisions (0)

No revisions yet.