Python Indentation

Chris Angelico rosuav at gmail.com
Sat Aug 13 07:16:52 EDT 2016


On Sat, Aug 13, 2016 at 8:52 PM, Cai Gengyang <gengyangcai at gmail.com> wrote:
> Indentation must be the same. This code doesn't work.
>
> if a == 1:
>   print("Indented two spaces.")
>      print("Indented four. This will generate an error.")
>     print("The computer will want you to make up your mind.")
>
> Why does the first example work and the 2nd example doesn't work ? Can someone explain in layman's terms what indentation is and why the first one works and the 2nd one doesn't ? Thanks alot

Indentation is whitespace at the beginning of the line. And the reason
this code doesn't work is that more indentation means more levels in,
like this:

# Top level
def frobnicate(stuff):
    # Inside the function
    for thing in stuff:
        # Inside the loop
        if thing.frobbable:
            # Inside the conditional
            thing.frob()
    # Where is this?
    return "All frobbed"

A casual eye will tell you that the return statement is outside the
loop, outside the condition, but inside the function. And that's
exactly how Python interprets it, too - but to do that, it absolutely
depends on the indentation levels being consistent. Normally you'll be
extremely consistent (eg four spaces for the first level, eight for
the second, then twelve, sixteen, etc); all Python actually demands is
that you use the same number of spaces and/or tabs (and they're not
equivalent - one tab matches one tab, one space matches one space) for
the same level of nesting.

My recommendation to you is that you pick some way of indenting and
use it everywhere. The most common would be either one tab per level,
or four spaces per level. (Also, do not get into arguments about which
one is better. They're not productive.)

Python makes things fairly easy on you. If you end a line with a
colon, you indent the next line. If you don't, you don't. Good rule of
thumb :)

ChrisA



More information about the Python-list mailing list