An interesting beginner question: why we need colon at all in the python language?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Jul 16 06:07:56 CEST 2011


Wanderer wrote:

> But if you have the colon, why do you need the brackets or backslashes
> in an if statement.
> 
> Why not
> 
> if condition1 or
>    condition2 or
>    condition3:
>     do_something()
> 
> The statement ain't over til there's a colon.


Because there are virtues in having the parser be nice and simple. Syntax
constraints help identify errors:

mystr = "this is a string

Should we say that no closing quote is needed, because the newline
unambiguously ends the string? Well, perhaps... but allowing such a rule
would mask errors:

mystr = "this is a %s % type(something)

Good language design requires constraints on what is allowed as well as
freedom from unnecessary syntax. 

The appropriate lines from the Zen are

Errors should never pass silently.
Unless explicitly silenced.

Newlines end parsing of the current token or expression. Including a newline
inside an expression is an error, unless you explicitly silence it by using
a backslash or using brackets. It's a bit too far to say that "any if
statement is an explicit way to silent newline errors".



-- 
Steven




More information about the Python-list mailing list