Indentation is a crucial aspect of Python programming language. Unlike other languages which use brackets or keywords to define block structures, Python uses indentation.
Simple whitespace, tab, or several spaces can differentiate between control structures, functions, and classes in your code, making it easier to read and debug. This unique feature of Python cuts down on unnecessary clutter.
This guide will help you understand how indentation works in Python.
Step 1: Basic Indentation Rule
Python uses spacing at the start of the line to determine when code blocks start and end. Code blocks are regions of code that are supposed to run together.
They are created by control structures such as for, if, while, function, and class statements. The basic rule for Python is that these constructs must be indented four spaces. We use spaces instead of tabs as spaces are the preferred indentation method. Alternatively, an IDE or text editor can also convert tabs to spaces.
Step 2: Creating an Indented Block
In Python, you start a new block of code by ending a line with a colon “:” and indenting the next line. Let’s illustrate this with an example:
1 2 |
if 5 > 2: print("Five is greater than two!") |
The print
statement is part of the if
statement block because it is indented under the if
statement.
Step 3: Understanding the Scope of Indentation
Every line within a block must be indented the same amount. If you want to add additional blocks inside a block (nested blocks), add more indents for those lines. To end a block, simply un-indent the next line. Here is an example:
1 2 3 4 |
if 5 > 2: print("Five is greater than two!") if 2 < 1: print("Two is less than one!") |
Example Code:
1 2 3 4 5 6 |
if 5 > 2: print("Five is greater than two!") if 2 < 1: print("Two is less than one!") else: print("Five is not greater than two!") |
The above code checks the first condition 5 > 2
which is true, hence it prints the string “Five is greater than two!” The next condition checks if 2 < 1
which is false hence it does not print anything. The else
is not executed as the if
was satisfied.
Conclusion
Indentation is not just a way of making your code look neater, it is the bedrock of Python syntax. It encourages programmers to write well-structured and readable code.
Always remember that the number of spaces isn’t by itself important – what is important is that other lines of code in the same block contain the same amount of indentation.