如何在python中修复'IndentationError:预期缩进的块'

时间:2019-04-22 09:55:54

标签: python-3.x

我发现了IndentationError

  

IndentationError:预期审计日在第33行出现一个缩进的块=   week2 ['calendar.MONDAY']

这是代码,错误在倒数第二行,我正在使用最新的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))

2 个答案:

答案 0 :(得分:1)

与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']

谢谢

答案 1 :(得分:0)

您错过了最后一个缩进块。

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

所以整个代码看起来像这样。

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的IDE(例如PyCharm),它将突出显示出现缩进错误的语法