Calculating the number of days in each month using Python requires importing the calendar module and using its monthrange function to get a tuple containing the day of the week for the first and last days, and the number of days in the month. Then, you can print the number of days in that month. For example, the number of days in April 2023 is calculated to be 30 days.
How to use Python to calculate the number of days in each month
Python provides a program called calendar
's built-in module can easily calculate the number of days in each month. The following are the specific steps:
Step 1: Import calendar
module
<code class="python">import calendar</code>
Step 2: Use monthrange
Function
calendar
The monthrange
function in the module returns a tuple containing the day of the week for the first and last days of the specified year and month. The third element of the tuple represents the number of days in the month.
<code class="python">year = 2023 month = 4 days_in_month = calendar.monthrange(year, month)[2]</code>
In the given example, days_in_month
will store the number of days in the month of April.
Step 3: Print the results
Use the print
function to print the number of days in each month:
<code class="python">print(f"4 月份有 {days_in_month} 天。")</code>
Example :
<code class="python">import calendar # 计算 2023 年 4 月的天数 year = 2023 month = 4 days_in_month = calendar.monthrange(year, month)[2] # 打印结果 print(f"{year} 年 {month} 月有 {days_in_month} 天。")</code>
Executing this code will output the following:
<code>2023 年 4 月有 30 天。</code>
The above is the detailed content of How to calculate the number of days in each month in python. For more information, please follow other related articles on the PHP Chinese website!