Python indentation deters newbies?

Peter Hansen peter at
Tue Aug 17 00:06:33 CEST 2004

beliavsky at wrote:

> Peter Hansen <peter at> wrote in message news:<nbudnY5S8Jl2Kb3cRVn-oQ at>...
>>So did you indent your code such that consecutive lines were
>>not indented to the same identation level even when they were
>>conceptually, logically, *algorithmically* part of the same
> I think you are getting a little religious about indentation. 

You bet I am. :-)  Always have been...

> I mostly indent Python the way I'd indent Fortran, but there are some
> inflexibilities in Python:
> (1) I use a blank line to separate functions. I don't like being
> forced to indent every line within the body of a function.

Hmm... without an example, I'm not sure what you suggest.  On
the face of it, not having every line indented would strike
me immediately as a serious formatting error that is highly
likely to affect the readability of the code.

> (2) Nested loops can *sometimes* be thought of as a single loop and
> indented that way. I don't think the indentation
> do i=1,n
> do j=1,n
> do k=1,n
>    x(i,j,k) = some_func(i,j,k)
> end do
> end do
> end do
> is necessarily bad. 

I do!  It doesn't show the structure of the code clearly enough.
If there are three loops, there should be three levels of nesting
so that the eye is immediately drawn to it and the mind can say
"aha... possible area for code improvement, look more closely".
Without the indentation, the eye will skip right over that when
scanning lots of text.  Probably other reasons too, but suffice
to say that I'd immediately reformat that in any code someone
in my group wrote.

> (3) Having a labelled end-of-loop statement lets you exit the desired
> number of nested loops in a clean way. In the following Fortran code
> you can exit any of the nested loops. How would you simulate this
> control flow in Python?
> ido: do i=1,n
>    ! some code
>    if (foo) exit ido ! exit outer loop
>    jdo: do j=1,n
>       ! some code
>       if (boo) exit jdo ! exit middle loop
>       do k=1,n
>          ! some code
>          if (goo) exit ! exit inner loop
>       end do
>    end do jdo
> end do ido

Why with a custom exception, obviously.  But what does that have to do
with indentation?


More information about the Python-list mailing list