- Daniel Arbuckle's Mastering Python
- Daniel Arbuckle
- 308字
- 2021-07-02 21:09:41
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.
- Boost程序庫完全開發指南:深入C++”準”標準庫(第5版)
- LabVIEW2018中文版 虛擬儀器程序設計自學手冊
- JavaScript+jQuery網頁特效設計任務驅動教程(第2版)
- 圖解Java數據結構與算法(微課視頻版)
- Architecting the Industrial Internet
- Getting Started with CreateJS
- OpenStack Cloud Computing Cookbook(Fourth Edition)
- Learning Laravel 4 Application Development
- 游戲程序設計教程
- 手把手教你學C語言
- Hands-On Functional Programming with TypeScript
- Linux C編程:一站式學習
- “笨辦法”學C語言
- Scratch趣味編程:陪孩子像搭積木一樣學編程
- JavaScript動態網頁編程