Python Program To Find Number Of Days In A Given Month And Year
Chapter:
Python
Last Updated:
22-09-2023 04:57:25 UTC
Program:
/* ............... START ............... */
import calendar
def find_number_of_days(year, month):
# Use the monthrange function from the calendar module
_, num_days = calendar.monthrange(year, month)
return num_days
# Input year and month from the user
year = int(input("Enter a year: "))
month = int(input("Enter a month (1-12): "))
# Check if the input month is valid
if 1 <= month <= 12:
num_days = find_number_of_days(year, month)
print(f"Number of days in {calendar.month_name[month]}, {year}: {num_days}")
else:
print("Invalid month input. Please enter a month between 1 and 12.")
/* ............... END ............... */
Output
Enter a year: 2023
Enter a month (1-12): 2
Number of days in February, 2023: 28
In this example, the user entered the year 2023 and the month 2 (which corresponds to
February), and the program correctly determined that February 2023 has 28 days.
Notes:
-
This program first imports the calendar module, then defines a function find_number_of_days that takes a year and a month as input and uses calendar.monthrange to determine the number of days in that month. It then takes user input for the year and month and prints the result.
Tags
Python program to find number of days in a given month and year #How to get the number of days in a month and year in Python? # Number of days in a given month of a year in python