首页 > 解决方案 > 如何在 python 中修复“IndentationError:预期有缩进块”

问题描述

我发现缩进错误

IndentationError: 在 auditday = week2['calendar.MONDAY'] 的第 33 行需要一个缩进块

这是代码,错误在倒数第二行,我使用的是最新的python3.7版本

# The calendar can give info based on local such a names of days and months (full and abbreviated forms)
for name in calendar.month_name:
    print(name)
for day in calendar.day_name:
    print(day)
# calculate days based on a rule: For instance an audit day on the second Monday of every month
# Figure out what days that would be for each month, we can use the script as shown here
for month in range(1, 13):
    # It retrieves a list of weeks that represent the month
    mycal = calendar.monthcalendar(2025, month)
    # The first MONDAY has to be within the first two weeks
    week1 = mycal[1]
    week2 = mycal[2]
    if week1[calendar.MONDAY] != 0:
        auditday = week1['calendar.MONDAY']
    else:
    # if the first MONDAY isn't in the first week, it must be in the second week
    auditday = week2['calendar.MONDAY']
print("%10s %2d" % (calendar.month_name[month], auditday))

标签: python-3.x

解决方案


和 if 循环一样,else 循环也应该缩进四个空格。

if week1[calendar.MONDAY] != 0:
    auditday = week1['calendar.MONDAY']
else:
# if the first MONDAY isn't in the first week, it must be in the second week
    auditday = week2['calendar.MONDAY']

谢谢


推荐阅读