Display Calendar Using Loop in Python
Below are some examples by which we can display the calendar using a loop in Python:
Python Program To Display Calendar For Loop
In this example, a calendar matrix for February 2024 is generated using Python’s `calendar` module. The matrix is printed in a tabular format with days of the week headers, where each day’s number is displayed right-aligned within a two-character space using for loop.
Python3
import calendar year = 2024 month = 2 #matrix format cal = calendar.monthcalendar(year, month) print ( "Mo Tu We Th Fr Sa Su" ) for week in cal: for day in week: if day = = 0 : print ( " " , end = " " ) else : print (f "{day:2} " , end = " " ) print () |
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
Python Program To Display Calendar Using While Loop
In this example, a calendar matrix for February 2024 is created using Python’s `calendar` module. The days of the week are displayed in a tabular format with the corresponding day numbers aligned within a two-character space. The variable `head` represents the header with week names, and the matrix is printed using nested loops to iterate through each week and day.
Python3
import calendar year = 2024 month = 2 #using to represent matrix form cale = calendar.monthcalendar(year, month) #print the week names head = "Mo Tu We Th Fr Sa Su" print (head) for week in cale: day_index = 0 while day_index < len (week): day = week[day_index] if day = = 0 : print ( " " , end = " " ) else : print (f "{day:2d} " , end = " " ) day_index + = 1 print () |
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
Python Program To Display Calendar Using Loop
Python is an object-oriented, high-level, interpreted, and simple programming language. In Python, we are going to use the “Calendar” module to display a calendar. In this article, we are going to cover all the possible ways to display a calendar using loops i.e., while loop, for loop, etc., and various operations on the calendar, in tabular format such as days and months of the whole year.
Contact Us