In Python, complex statements such as if, for, def, and class require a colon :
.
if True:
print('Hello, world!')
The header of each section begins with a uniquely identifying keyword and ends with a colon. 8. compound statement-Python language reference
The official documentation explains why you have to write the colon :
.
When writing in one line with a semicolon ;
in one line, it is easier to understand. At this time, it would be quite confusing without :
.
def f(x): y = x + 1; z = y + 2; return z;
f(0)
>>> def f(x): y = x + 1; z = y + 2; return z;
...
>>> f(0)
3
>>>
In the official document, the method of writing in multiple lines is given as an example in the talk of ABC language etc., but I personally think that the one-liner using this semicolon ;
was more critical ( I rarely use it, but lol).
It's a simple sentence, but I think it's easier to understand if there is a colon :
in the case of a lambda expression.
g = lambda x: x + 1
g(0)
>>> g = lambda x: x + 1
>>> g(0)
1
>>>
I've used indentation instead of parentheses to group sentences. Therefore, isn't it somewhat strict to claim that "it is easier to analyze if you use a colon:
only at the beginning"? I personally think.
Don't you need this colon :
? Is often criticized. I don't think I'm honest either. This is because I rarely write compound sentences with one liner.
Python is now quite versatile, but with the spirit of "you don't have to have anything you want," I feel like I was cautious about adding new features. I think that spirit is clearly expressed by the following words of PEP 20.
There should be one-- and preferably only one --obvious way to do it. PEP 20 -- The Zen of Python
It may be more accurate here to say "I don't need the ability to write in one liner with a semicolon;
" rather than not needing a colon :
.
I thought about the process of writing a colon, but ... I want to be able to write with a semicolon ;
even with a one-liner. To do so you need to write a colon :
. Writing or not writing a colon :
is inconsistent with and without one-liner.
Special cases aren't special enough to break the rules. PEP 20 -- The Zen of Python
So let's unify by adding a colon :
. I personally wonder if that was the case.
Recommended Posts