pythonsyntax

What is the purpose of the colon before a block in Python?


What is the purpose of the colon before a block in Python?

Example:

if n == 0:
    print "The end"

Solution

  • The colon is there to declare the start of an indented block.

    Technically, it's not necessary; you could just indent and de-indent when the block is done. However, based on the Python koan “explicit is better than implicit” (EIBTI), I believe that Guido deliberately made the colon obligatory, so any statement that should be followed by indented code ends in a colon. (It also allows one-liners if you continue after the colon, but this style is not in wide use.)

    It also makes the work of syntax-aware auto-indenting editors easier, which also counted in the decision.


    This question turns out to be a Python FAQ, and I found one of its answers by Guido here:

    Why are colons required for the if/while/def/class statements?

    The colon is required primarily to enhance readability (one of the results of the experimental ABC language). Consider this:

    if a == b 
        print a
    

    versus

    if a == b: 
        print a
    

    Notice how the second one is slightly easier to read. Notice further how a colon sets off the example in this FAQ answer; it’s a standard usage in English.

    Another minor reason is that the colon makes it easier for editors with syntax highlighting; they can look for colons to decide when indentation needs to be increased instead of having to do a more elaborate parsing of the program text.