官术网_书友最值得收藏!

Code indentation

As programmers, when we read code we look at how it's indented to tell us how the code blocks are nested. However, most other programming languages use actual symbols to tell the language parser where a block begins and ends. In coding, the same information in two different places is a violation of the basic best practices of any programming language. So, Python omits the beginning and ending block markers and uses indentation (as shown in the following code screenshot) to inform the parser as well as the programmer:

There is one problem that arises from that, though!

There are different ways of encoding indentation in a text file. These are as follows:

  • Use Space characters
  • Tab characters
  • A combination of both

The codes we're looking at in the preceding code image mixes spaces and tabs, which, in Python 2 was valid, but a terrible idea, and which, in Python 3, is a syntax error. I've configured the editor to highlight tab characters in color, so we can easily see which indentation comes from spaces and which comes from tabs, to see why mixing spaces and tabs is not good, even when it's allowed.

All we have to do is change the tab width and it will look something like the following code image:

Even though the indentation looked good in the previous code image, now it's clearly wrong. There's no ambiguity if all indentation comes from tab characters. So, using only tabs is valid, even in Python 3. However, it is the recommendation of PEP 8 and the Python community that we always use exactly four spaces to indicate one level of indentation. Any halfway decent editor can insert those spaces for us when we press the Tab key. There are several more recommendations, which we're going to go through quickly in the next sub-section.

主站蜘蛛池模板: 嘉鱼县| 建瓯市| 措美县| 竹溪县| 青铜峡市| 嘉兴市| 丹东市| 揭东县| 西藏| 浦城县| 清水河县| 茶陵县| 肇庆市| 高碑店市| 宁河县| 汤原县| 大新县| 温宿县| 光山县| 罗甸县| 涞源县| 浦城县| 若尔盖县| 安陆市| 库尔勒市| 西华县| 乐山市| 黄龙县| 泽库县| 商都县| 眉山市| 平谷区| 乐亭县| 仲巴县| 道孚县| 芦山县| 德钦县| 临安市| 沂南县| 镇远县| 莱阳市|