Reading Time: 1 minutes
leap year or not in Python
Python program to determine whether a given year is a leap year or not. A leap year is one with 29 days in the month of February, and mathematically, it is a multiple of 400 or 100 or 4.
## A leap year is one with 29 days in the month of February, and mathematically, it is a multiple of 400 or 100 or 4. ## THOUGHT PROCESS: Prompt the user for an year -> cast the input into an integer -> set a default flag for later use -> operate on number turn by turn using if statement, set flag accordingly -> use the flag to print the correct conclusion. # Take the input from the user year = int(input("Enter an year: ")) isAleapYear = False # this variable serves as a flag in the program i.e. its value will be either true or false based on conditions, and at some point in the program, this flag will decide the flow of the program i.e. which statements to execute and which ones to skip according to its value. Since Python is an interpreted language, any variable we use inside the program needs to be declared beforehand so that the interpreter knows that there is a variable by this name. We can initialize it with the wrong value, it just needs to be in the memory so that the interpreter can recognize it. We can declare this variable anywhere before its use, but the convention is to declare variables at the top, before the actual logic, for easy code walkthrough. # Determine whether the supplied year is a leap year or not if year % 400 == 0: isAleapYear = True elif year % 100 == 0: isAleapYear = True elif year % 4 == 0: isAleapYear = True else: isALeapYear = False # Printing the result if isAleapYear: print(year, "is a leap year.") else: print(year, "is not a leap year.")
Try it here.