Search code examples
pythonif-statementarraylistreturn

Python Returning Variable From Nested If Statements


I am a beginner and wondering how I can to manage the program to go to a function depending on whether the year is a leap year. Here is the code I have. Maybe I can direct this function to return a variable that says the year is either a regular year or a leap year and depending on that resulting variable I can choose which function it would go to next? I'm not sure how to do that or if there is a better way to do this.

def get_year():
    print("Enter a year:")
    year = int(input())
    return year


def leap_year(year):
    if (year % 4) == 0:
        if (year % 100) == 0:
            if (year % 400) == 0:
                print("This is a leap year")
            else:
                print("This is not a leap year")
        else:
            print("This is a leap year")
    else:
        print("This is not a leap year")


def main():
    months = ["January", "February", "March", "April", "May",
              "June", "July", "August", "September", "October",
              "November", "December"]
    days_leap = [31, 29, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30]
    days = [31, 28, 31, 30, 31, 30, 31, 30, 31, 30, 31, 30]
    year = get_year()
    leap_year(year)


main()

Solution

  • You could do this:

    def leap_year(year):
        if (year % 4) == 0:
            if (year % 100) == 0:
                if (year % 400) == 0:
                    print("This is a leap year")
                    return True
                else:
                    print("This is not a leap year")
                    return False
            else:
                print("This is a leap year")
                return True
        else:
            print("This is not a leap year")
            return False
    

    That way, you can later say:

    if leap_year(year):
        doAThing()
    else:
        doADifferentThing()