Thursday, 23 December 2021

Leap Year Check Python - Sample Code To Check Leap Year In Python & Return The Number of Days In A Particular Month | Python 100 Days Challenge Udemy Solution

We start with by writing a function called is_leap() that checks if the year entered is a leap year or not. You can check the link to understand more about leap year and how the below code has been built.

#Function to check whether the entered year is a leap year or not which will return
True or False(Boolen) based on the calculation.
def is_leap(year):
  leap_flag = False
  if year % 4 == 0:
    if year % 100 == 0:
      if year % 400 == 0:
        leap_flag = True
      else:
        leap_flag = False
    else:
      leap_flag = True
  else:
    leap_flag = False
  return leap_flag

#days_in_month() - This function has if-else blocs, where first blocks contains days
for non leap year and else block has days for leap year.

def days_in_month(year, month):
  leap_flag_val = is_leap(year)
  #The first if loop checks if the entered year is not a leap year and in the else
   loop it checks for the days in months list for a leap year.
  if leap_flag_val==False:
    month_days = [312831303130313130313031]  
    return month_days[month-1]
  else:
    month_days = [312931303130313130313031]  
    return month_days[month-1]

#You will enter the input values hear
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)

Output:

No comments:

Post a Comment