86

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

Example:

if n == 0:
    print "The end"
5
  • 27
    I found this colon very annoying when first learning Python: it seems inconsistent with the "space based syntax" philosophy of the entire project. None of the reasons people give are compelling, unless it is "Oops, my bad: it's too late to change."
    – eric
    Commented May 18, 2015 at 13:08
  • 6
    Well, that's precisely what Guido said: "it's too late to change".
    – Gabriel
    Commented Jan 21, 2017 at 15:55
  • 8
    @Gabriel -- Your comment is misleading. The substantive content of Guido's answer at the link you provided expounds the decision to implement the colon, indicating that it was and still is a valid choice. "It's too late to change" appears as minor parenthetical content, and the full quote is actually, "but anyway, it's too late to change"; the "but anyway" portion of the quote, which you left out in your comment, clearly indicates that it was merely an observation or matter of fact on Guido's part.
    – rory.ap
    Commented Mar 31, 2017 at 11:47
  • 3
    Without that context, your comment is misleading because it appears to bolster neuronet's point which is entirely predicated on the inclusion of the colon being a mistake that can no longer be changed, which it clearly isn't. Future readers of this post may quickly read your comment (ignoring the answer(s) below) and draw a wrong conclusion.
    – rory.ap
    Commented Mar 31, 2017 at 11:47
  • 1
    I don't' think my comment is misleading, and I also don't pretend to know what Guido thinks. It's been 15 years since Guido's comment. I'm thinking the colon is not going away anytime soon. Cheers.
    – Gabriel
    Commented Mar 31, 2017 at 12:17

5 Answers 5

77

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.

9
  • 1
    Yeah, but (1) oneliners are a bad idea. (PyLint criticizes them, the FAQ does not even name them as an argument) Editors (2) are advanced enough today that more elaborate parsing (like PyLint does) can be required. Readability (3) is mainly higher in the FAQ, because Pygments chokes on the wrong syntax. That it is standard usage in English (4) might be the best point for having this construction. The best point against changing it, must be as Guido put it: "its too late to change".
    – Bengt
    Commented Aug 19, 2012 at 23:52
  • 16
    Ah. Explicit is better than implicit. You know what else is explicit? Block closing delimiters. Cult programming. Commented Jun 29, 2014 at 22:07
  • 2
    @MarkGerolimatos block closing delimiters are explicit, but so is de-indentation.
    – Andy
    Commented Feb 17, 2017 at 18:37
  • 2
    @andy de-intentation is FAR from explicit: tabs versus spaces, one fewer / one too many space (very hard to see with smaller fonts and variable-spaced fonts), lack of "find the end of this block" capabilities in non-Python-aware editors. These are likely the reasons that The Google put curly braces "back" in to Go(Lang), when they were originally going to use the Python indentation model. Commented Feb 27, 2017 at 8:44
  • 6
    The first example actually seems easier to read, at least to me. And I don't think syntax highlighting would be a problem with modern editors.
    – user76284
    Commented Jul 31, 2018 at 16:53
28

Consider the following list of things to buy from the grocery store, written in Pewprikanese.

pewkah
lalala
    chunkykachoo
    pewpewpew
skunkybacon

When I read that, I'm confused, Are chunkykachoo and pewpewpew a kind of lalala? Or what if chunkykachoo and pewpewpew are indented just because they are special items?

Now see what happens when my Pewprikanese friend add a colon to help me parse the list better: (<-- like this)

pewkah
lalala:   (<-- see this colon)
    chunkykachoo
    pewpewpew
skunkybacon

Now it's clear that chunkykachoo and pewpewpew are a kind of lalala.

Let's say there is a person who's starting to learn Python, which happens to be her first programming language to learn. Without colons, there's a considerable probability that she's going to keep thinking "this lines are indented because this lines are like special items.", and it could take a while to realize that that's not the best way to think about indentation.

5
  • 2
    I almost want to upvote that for your hilarious examples... but the other answers are much stronger. Still, thanks for the smile! Commented Sep 23, 2009 at 8:16
  • 13
    the thing is that the indents are required in python, so this example doesn't really wash for me. If the colons are required then the indenting should be optional I say :-) why have two indications of the same thing? Isn't that more complex than just having one?
    – Sam Joseph
    Commented Feb 14, 2012 at 17:06
  • 8
    +Sam Joseph: The colon marks the start, not the end. So you couldn't make indenting optional. Only colons could be optional.
    – Mark
    Commented Sep 22, 2016 at 21:20
  • Unfortunately, the dialect of Pewprikanese I’m most familiar with uses colons as a marker for plurals. Thus, in your second example, the colon does not help me parse the list better at all. Colons don’t have any more universal meaning than any other linguistic symbol. Actually, you are relying on the familiarity of most readers with its common use in English and other dominant languages. Now, that being taken into consideration, one must agree that, in those languages, indentation serves exactly the same purpose as the one Python uses it for. Commented Aug 24, 2023 at 15:57
  • 1
    … For examples of languages where colon-shaped symbols have a whole different meaning, see en.wikipedia.org/wiki/Colon_(letter) Commented Aug 24, 2023 at 15:59
18

Three reasons:

  1. To increase readability. The colon helps the code flow into the following indented block.
  2. To help text editors/IDEs, they can automatically indent the next line if the previous line ended with a colon.
  3. To make parsing by python slightly easier.
2
  • 1
    +1 - "To increase readability" is the correct reason. But as I'm drafting my own language, I wonder, why is the burden on the writer to make the code readable? Syntax highlighting improves readability, but there's no requirement that the author bold certain portions of the code, for example. It seems to me that the IDE aught to handle giving that additional visual queue for where a block begins, just like it highlights certain keywords by coloring or bolding or whatevering them. And if the reader would rather do without or with other indicators/styles - they could change the skin. Commented Oct 22, 2013 at 12:49
  • 12
    I believe it is only more readable to people who are conditioned to expect it. For those new to Python, which is weird because it only uses spaces, the sudden use of a colon instead of just spacing doesn't make it any more readable, and only leads to mistakes. The only real reason is that it is too late to change it. Syntax parsers could easily work without the colon, come on people: IDEs can be sensitive to a little thing I like to call "carriage return."
    – eric
    Commented May 18, 2015 at 13:06
8

As far as I know, it's an intentional design to make it more obvious, that the reader should expect an indentation after the colon.

It also makes constructs like this possible:

if expression: action()

code_continues()

since having the code for the if immediately following the colon makes it possible for the compiler to understand that the next line should not be indented.

3
  • Just want to note here that the ability to skip the new line seems to be the best justification for this piece of syntax as annoying as it may seem. I used this example for the justification: def long_words(lst): return list(filter((lambda word: len(word) > 5), lst)) works as a one-liner for people who appreciate compactness of simple functions.
    – BNazaruk
    Commented Dec 6, 2021 at 2:48
  • 3
    If the colon was optional, one-liners would still be possible. Commented Jan 13, 2023 at 15:31
  • 1
    Yes, the colon should be optional. The OP is correct and Guido and everyone else is wrong. (my two cents) Commented Jul 7, 2023 at 3:32
5

Not all redundancies are bad. Python aspires to resemble a natural language. And natural languages are full of redundancies that help us better understand each other. Take, for instance, the capitalization of the first letter in a sentence. The end of a sentence is already clear from the full stop, yet capitalization helps us better grasp when a new sentence starts.

Guido Van Rossum, the creator of Python, already experimented with enhancing structural clarity with a colon for the ABC language — a precursor to Python, also designed for beginners. During initial tests, it became apparent that beginners progressed more rapidly when a colon was introduced.

In the absence of the colon, the meaning of indentation were unclear for beginners learners. The addition of the colon significantly clarified this: somehow, the colon draws attention to what follows, seamlessly tying together the phrases before and after it.

For more details, you can refer to the source: Early Language Design and Development.

While I acknowledge that mature programmers, including myself, initially find this construct unusual and somewhat annoying. Yet we tend to get accustomed to it over time. Nowadays, Python is often one of the first languages that people learn, so for most people the colon is not issue but a visual aid.

Moreover, the colon proves useful in one-liners and is less bothersome than the semicolon.

The colon a bit resembles a binary operator for a compound statement, and improves mark up when the condition of if or while takes multiple lines:

if (one_extra_long_expression != 
    that_is_another_thing):
    this_thing |= abs(something)

Many programming languages use colons are often used as a separator in ternary if operator, so use of colon as lightweight separator should not be that shocking.

It's worth noting that there are colon-less encodings for CPython, as well as full-fledged colon-less dialects like Cobra, though these have not gained widespread adoption.

2
  • 1
    To me that indicates that someone disliked it so much they omitted it. They fact that cobra was not successful does not speak much to the viability of the optional colon. I'm not sure I understand how the break on several lines comment is related. Please explain. Commented Jul 7, 2023 at 3:36
  • 1
    I doubt the ABC test was very scientific. The colon seems ugly and unnecessary to me. I bet beginners, if they were left to their own accord and just typed what they thought made sense, would not think to add a colon. Of course, they also might not add a new line and indent either. It's not a huge deal, but every time I forget one, I get a little ruffled (lol). Also, if it is optional, don't we have the best of all worlds? Commented Jul 7, 2023 at 3:40

Not the answer you're looking for? Browse other questions tagged or ask your own question.