on python indent

Python indent seems an easy syntax. If you use the same number of spaces/tabs(don’t mix spaces and tabs) for code lines in the same block, you’ll have no problem. That gives newbies an illusion:the same sequence of blank characters(including spaces and tabs) forms a code block. But that is a misunderstanding. In fact, a code block is formed by the same indent(not character sequence). 8 space characters form the same indent as one tab character in Windows. Things become complicated if you open python source files in different text editors. For example, Notepad++ displays different indent from notepad accompanied by Windows, for the same sequence of characters. Python interpreter calculates the indent in the same way as the notepad accompanied by Windows. So if you edit your python script in Notepad++, you may encounter problem even it looks as if the same indent is placed before code lines. To fix the indent issue, you should check your source file in notepad.

The second misunderstanding is you should use the same indent for the code block in the else sub-clause and the code block in the if sub-clause. The same indent can indeed make the code look clean but is not necessary. The code block in the else sub-clause only requires an indent from the else statement(otherwise you will get the error “IndentationError: expected an indented block”), but the indent need not the same as that of the code block in the if sub-clause.

In the same code block, if the subsequent line has more indent than the previous line, you will get the error “IndentationError: unexpected indent”. If the subsequent line has less indent than the previous line, you will get the error “IndentationError: unindent does not match any outer indentation level”.

The top level statements must not have indent.

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

Leave a Reply