Search code examples
pythonleap-year

Finding the next leap year: Python


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

Solution

  • 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