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

后端 未结 5 1965
孤街浪徒
孤街浪徒 2020-11-28 09:26

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

Example:

if n == 0:
    print \"The end\"
5条回答
  •  鱼传尺愫
    2020-11-28 10:17

    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()
    

    Note (as a commenter did) that this is not exactly the shining gold standard of good Python style. It would be far better to have a blank, there:

    if expression: action()
    
    code_continues()
    

    to avoid confusion. I just wanted to make it clear, with the first example, that it's possible to write like that, 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.

提交回复
热议问题