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

后端 未结 5 1968
孤街浪徒
孤街浪徒 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条回答
  •  旧时难觅i
    2020-11-28 10:02

    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.

提交回复
热议问题