SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
.loops
Exercise:
Programming Excercises
Question:30 | ISBN:978013274719 | Edition: 6

Question

(Display the first days of each month) Write a program that prompts the user to enter the year and first day of the year, and displays the first day of each month in the year on the console. For example, if the user entered year 2013, and 2 for Tuesday, January 1, 2013, your program should display the following output:
January 1, 2013 is Tuesday
...
December 1, 2013 is Sunday

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Display the first days of each month Program code:

# Prompt the user to enter the year and the first day of the year
year = int(input("Enter the year: "))
firstDay = int(input("Enter the first day (1-7, where 1 is Monday and 7 is Sunday): "))

# Create a list of month names
months = [
    "January", "February", "March", "April",
    "May", "June", "July", "August",
    "September", "October", "November", "December"
]

# Create a list of days of the week
daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

# Display the first day of each month
for month in range(1, 13):
    # Display the first day of the current month
    print(months[month-1] + " 1, " + str(year) + " is a " + daysOfWeek[firstDay-1])

    # Calculate the number of days in the current month
    if month == 2:  # February
        if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
            daysInMonth = 29  # Leap year
        else:
            daysInMonth = 28
    elif month in [4, 6, 9, 11]:  # April, June, September, November
        daysInMonth = 30
    else:
        daysInMonth = 31

    # Update the first day for the next month
    firstDay = (firstDay + daysInMonth) % 7

 

Executed Output:

Enter the year: 2013
Enter the first day (1-7, where 1 is Monday and 7 is Sunday): 2
January 1, 2013 is a Tuesday
February 1, 2013 is a Friday
March 1, 2013 is a Friday
April 1, 2013 is a Monday
May 1, 2013 is a Wednesday
June 1, 2013 is a Saturday
July 1, 2013 is a Monday
August 1, 2013 is a Thursday
September 1, 2013 is a Sunday
October 1, 2013 is a Tuesday
November 1, 2013 is a Friday
December 1, 2013 is a Sunday

 

0 0

Discussions

Post the discussion to improve the above solution.