To print a complete one-year calendar in Python, you can use the calendar
module, which is part of the Python standard library. Here’s an example of how you can do it:
import calendar # Create a calendar object for the year you want to print year = 2023 # Change this to the desired year cal = calendar.TextCalendar(calendar.SUNDAY) # You can change the starting day of the week if needed # Loop through each month and print the calendar for that month for month in range(1, 13): # 1 to 12 for January to December print(cal.formatmonth(year, month))
In this code:
- Import the
calendar
module. - Define the year for which you want to print the calendar (change the
year
variable to your desired year). - Create a
TextCalendar
object with the starting day of the week (you can change it tocalendar.MONDAY
if you want weeks to start on Monday). - Use a loop to iterate through each month (from 1 to 12) and print the calendar for that month using
cal.formatmonth(year, month)
.
Print a complete 1-year calendar in Python user input
If you want to allow the user to input the year for which they want to print the calendar, you can modify the code to take user input. Here’s an updated version of the code:
import calendar # Prompt the user for the year year = int(input("Enter the year (e.g., 2023): ")) cal = calendar.TextCalendar(calendar.SUNDAY) # Loop through each month and print the calendar for that month for month in range(1, 13): print(cal.formatmonth(year, month))
In this updated code:
- We use the
input
function to prompt the user to enter the year. - We convert the user’s input to an integer using
int()
becauseinput
returns a string. - The rest of the code remains the same as before, where it prints the calendar for the specified year and each month.