简体   繁体   中英

Nested for loop IndentationError: expected an indented block when using calendar module

I am very new to python, so please forgive any basic mistakes. I took this block of code from a website (and it looks fairly straightforward) so I thought it would work. Basically, I want this code block to print out all the dates between 2015 and 2016. So far as I can tell, the indentation looks fine. I've tried adjusting the indentations as well, but I haven't had any luck in getting this to work. Any help would be greatly appreciated.

import calendar

cal = calendar.Calendar()

for year in range(2015,2016):
    for month in range(1,13):
        monthdays = [d for d in cal.itermonthdays(year,month) if d != 0]    
        for day in monthdays:
            r = str(year) + str(month) + str(day)
            print(r)

Whenever the code runs, I get this error:

>>> for year in range(2015,2016):
... for month in range(1,13):
File "<stdin>", line 2
    for month in range(1,13):
    ^
IndentationError: expected an indented block
>>> monthdays = [d for d in cal.itermonthdays(year,month) if d != 0]
>>> for day in monthdays:
... r = str(year) + str(month) + str(day)
File "<stdin>", line 2
    r = str(year) + str(month) + str(day)
    ^
IndentationError: expected an indented block

Thanks in advance.

Indentation is important in Python. If you have code C or Java before, a block is between { and } , but in Python it's different, indented lines after : are considered as a "block". Lines after if , while , def , etc must be indented more, either by spaces or tab.

The problem is that you possibly copy-and-paste that code into the IDE or terminal and the indentation is not preserved.

Look at these lines:

   >>> for year in range(2015,2016):
   ... for month in range(1,13):

Both for are on the same indent level, no space/tab before them. It's the problem. It should be:

   >>> for year in range(2015,2016):
   ...     for month in range(1,13):

The indentation can be a space, two spaces, or more, or tabs, as long as they are consistent.

And so on...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM