Indentation
in Python
In
Python, indentation is used to group statements together. Many popular
languages, including C and Java, use curly braces {} to define a code
block, whereas Python employs indentation.
We must
define a group of statements for functions and loops when writing Python
programming. This is accomplished by indenting the statements in that block
properly.
The
indentation level of a line is determined by the leading whitespaces (space and
tabs) at the beginning of the line. To group the statements for that code
block, you must increase the indent level. Reduce the indentation to collapse
the grouping in the same way.
To
construct or increase the indentation level of the code, four white spaces or a
single tab character are commonly applied. Let's look at an example to see how
the code indentation and statement grouping work.
Indentation
Rules in Python
- Backslash cannot be used to break indentation into numerous lines.
- IndentationError will be thrown if the initial line of Python code does not have indentation.
- Indentation should not be created by combining tabs and whitespaces. It's because non-Unix text editors operate differently, and mixing them can result in incorrect indentation.
- Indentation should be done with whitespaces rather than the tab character.
- The recommended practice is to start with four whitespaces and then add another four whitespaces to raise the indentation.
Advantages
of Indentation in Python
- Indentation is needed to properly arrange code in most programming languages. It's used for grouping in Python, and it automatically enhance the overall the code.
- The indentation rules in Python are relatively straightforward. Most Python IDEs will automatically indent your code for you, making writing properly indented code a simple.
Disadvantages
of Indentation in Python
- Because whitespaces are utilised for indentation, it's a pain to repair if the code is long and the indentation is messed up. Copying code from online sources, Word documents, or PDF files is the most common cause.
- Because most popular programming languages utilise braces for indentation, someone coming from a different side of the development world will find it difficult to acclimate to the idea of using whitespaces for indentation at first.