268. Python Program to Print a Calendar Month
HardPhase 3 · Challenge
This one needs care, but you know every tool it uses: lists, a for loop, join() and f-string widths. Write out one week on paper before you start.
Overview
Calendar apps, booking pages and school planners all draw a month as a grid of weeks. Getting every number into the right column is a good test of careful text formatting.
Problem Statement
Hana is making a planner page. For one month, Hana knows the number of days and the weekday of day 1. Weeks start on Monday.
Read the two lines. First print the header:
Mo Tu We Th Fr Sa Su
Then print the weeks, one line per week. The rules for a week line:
- Each day takes exactly 2 characters. A day from 1 to 9 gets a space in front, like
5. Days 10 and up already have 2 digits. - Put exactly one space between two days.
- In the first week, each weekday before day 1 is an empty cell of 2 spaces, also followed by one space.
- The last week stops after the last day of the month.
So every day sits under its weekday in the header.
Examples
Example 1. Input:
30
Wed
gives:
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Why: day 1 is a Wednesday, so Monday and Tuesday are empty cells. That is 2 + 1 + 2 + 1 = 6 spaces, then 1. Day 30 is a Thursday, so the last line stops there.
Example 2. Input:
28
Mon
gives:
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
Why: the month starts on a Monday and has exactly 4 weeks of 7 days, so it fills 4 full lines and nothing more.
Input
Two lines:
- The number of days in the month: 28, 29, 30 or 31.
- The weekday of day 1:
Mon,Tue,Wed,Thu,Fri,SatorSun.
Use input() with no prompt text: the tests type the input for you, and a prompt would end up in your output.
Output
The header and then 4 to 6 week lines. The spaces at the start of a line matter, so check them with care. A space at the end of a line is fine: the tests ignore it. The tests try 8 different inputs, also months that start on a Saturday or a Sunday and need 6 lines.
Try it first. The solution opens when you solve this question, or after 3 tries with Submit.