Finding the next leap year: Python

146 Views Asked by At

I was attempting a course about Python and I encountered a question in which as the name suggests I have to find the next leap year. But the code is not working properly with a few years and returns unwanted results.

Although this code works with some of the years such as 2020 or 2023 it doesn't quite work with the others such as 1896 or 498. Any type of help would be appreciated.

year = int(input("Year: "))
Count = year + 1

while True:
    if Count % 4 == 0:
        if Count % 100 == 0 and year % 400 == 0:
            print(f"The next leap year after {year} is {Count}")
            break
        elif year % 100 == 0:
            Count += 1
        else:
            print(f"The next leap year after {year} is {Count}")
            break
    else:
        Count += 1
2

There are 2 best solutions below

0
Mahammadhusain kadiwala On BEST ANSWER

Solution is here

year = int(input("Year:"))
next_leap_year = year + 1
while True:
    if next_leap_year % 4 == 0 and next_leap_year % 100 == 0:
        if next_leap_year % 400 == 0:
            print(f"The next leap year after {year} is {next_leap_year}") 
            break
        else:
            next_leap_year = next_leap_year + 4
            print(f"The next leap year after {year} is {next_leap_year}")
            break
    elif next_leap_year % 4 == 0:
        print(f"The next leap year after {year} is {next_leap_year}")
        break
    else:
        next_leap_year += 1
0
SIGHUP On

You can simplify the code with a single expression that determines if any given year is leap as follows:

yy = int(input('Enter start year: '))

while True:
    yy += 1
    if yy % 400 == 0 or (yy % 100 != 0 and yy % 4 == 0):
        print(f'The next leap year is {yy}')
        break