Python Syntax – Is Colon in Python Blocks Technically Necessary?

pythonsyntaxtheory

This is really just a theoretical question by a python newbie who wants to understand more.

I keep forgetting the colon after the block initial statements in python. Those are what I mean:

  • for <variable> in <sequence>:
  • if <blah blah>:

My thought is that one reason I keep forgeting is, that they are de-facto implicit: colon or not, the statement ends with that line.

My question – which I ask in order to learn how python syntax works – is, whether the colon is really unnecessary? Were I to change the python syntax so that the colon is no longer necessary, would anything break? Would that make some statements ambiguous or impossible?

Best Answer

Yes, the colon is required to disambiguate certain constructs. Consider, for example, if x - y < z: pass. Without the colon we cannot decide how to parse this without knowing the context of what x, y, and z are. if x: -y < z... is valid if x is boolean, if x - y < z: is valid otherwise.

As it's a very good idea for a programming language to not require you to execute an application up to the point you're compiling to be able to parse it, the colon is very required. You could drop it, but you'd need other ways to disambiguate.