Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Conditional Statements

Check if a year is a leap year - Python Program

Example 1 :

year = int(input("Enter year: ")) if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): print("Leap year") else: print("Not a leap year")

Output

 
OUTPUT  :
Enter year: 2024
Leap year

Example 2 : Advanced Program

def is_leap_year(year): """ Checks if a given year is a leap year. Args: year: An integer representing the year. Returns: True if the year is a leap year, False otherwise. """ if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): return True else: return False # Get input from the user try: year_to_check = int(input("Enter a year: ")) # Check if it's a leap year and print the result if is_leap_year(year_to_check): print(f"{year_to_check} is a leap year.") else: print(f"{year_to_check} is not a leap year.") except ValueError: print("Invalid input. Please enter a valid year (an integer).")

Output

 
OUTPUT 1 :    
Enter a year: 2024
2024 is a leap year.


OUTPUT 2 :   
Enter a year: 1900
1900 is not a leap year.


OUTPUT 3 :   
Enter a year: 2000
2000 is a leap year.


OUTPUT 4 :   
Enter a year: abc
Invalid input. Please enter a valid year (an integer).

Explanation

  • is_leap_year(year)Function :
    • This function takes an integer yearas input.
    • It implements the leap year rules using a single ifcondition with logical and (and) and or (or) operators.
    • year % 4 == 0 and year % 100 != 0: This part checks if the year is divisible by 4 but not by 100 (e.g., 2024).
    • year % 400 == 0: This part checks if the year is divisible by 400 (e.g., 2000).
    • The oroperator combines these two conditions, meaning if either one is true, the year is a leap year.
    • It returns Trueif the year is a leap year, False
  • User Input and Output:
    • year_to_check = int(input("Enter a year: ")): This line prompts the user to enter a year and converts the input string to an integer.
    • A try-exceptblock is used to handle potential ValueError if the user enters non-integer input.
    • The is_leap_year()function is called with the user's input.
    • An if-elsestatement then prints whether the entered year is a leap year or not based on the function's return value.