181k views
20 votes
(Find the number of days in a month) Write a program that prompts the user to enter the month and year and displays the number of days in the month. For example, if the user entered month 2 and year 2000, the program should display that February 2000 has 29 days. If the user entered month 3 and year 2005, the program should display that March 2005 has 31 days. Sample Run 1 Enter a month in the year (e.g., 1 for Jan): 4 Enter a year: 2005 April 2005 has 30 days Sample Run 2 Enter a month in the year (e.g., 1 for Jan): 2 Enter a year: 2006 February 2006 has 28 days Sample Run 3 Enter a month in the year (e.g., 1 for Jan): 2 Enter a year: 2000 February 2000 has 29 days

1 Answer

11 votes

Answer:

Follows are the code to this question:

m= int(input("Enter month: "))#defining a m variable that takes months value

y= int(input("Enter year: "))#defining a y variable that takes years value

if m in [1, 3, 5, 7, 8, 10, 12]:#use if block that check m value is in list

n_day = 31#defining a variable n_day that holds a value

elif m in [4, 6, 9, 11]:#use elif block that check m value is in list

n_day = 30#defining a variable n_day that holds a value

else:#defining else block

if y% 4 == 0 and (y % 400 == 0 or y % 100 != 0):#use if block to check leap year condition

n_day = 29#holds value in n_day variable

else:#defining else block

n_day = 28#holds value in n_day variable

m_name = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October",

"November", "December"]#defining a m_name as a list that holds string value

print(m_name[m - 1], y, "has", n_day, "days.")#print output with message.

Output:

Enter month: 6

Enter year: 2009

June 2009 has 30 days.

Explanation:

In this code two-variable "y and m" is defined that holds year and month value as an input from the user-end, and use the conditional statement to check m value, which is defined as follows:

  • In the first condition, if block, it checks m value is available in a given list if the condition is true it holds value "31" in n_day variable.
  • In the second condition, elif block is used checks m value is available in another given list if the condition is true it holds value "30" in n_day variable.
  • In the else block it check leap year condition and hold value in the "n_day variable", in the next step "m_name" variable is defined that stores string value, and uses the print method to print its calculated values.
User Ashfaque Rifaye
by
4.7k points