What Does Indentation Mean in Python?: Optimize Your App Performance
What Does Indentation Mean in Python?: Optimize Your App Performance
What Does Indentation Mean in Python?: Optimize Your App Performance
Ad by DatadogHQ.com
Indentation in a writing context typically describes the space between the page border (or page
margin) and the start of the text. In a programming context, it describes the space between the
edge of the editor and the start of the code.
Python is unusual (if not unique) among programming languages by having what is sometimes
called "significant whitespace", where the amount of space before the code starts affects the
structure of the program.
Many programming languages allow you to group statements together into blocks and run those
blocks in a loop or conditionally. Usually those blocks are delimited by some kind of identifier that
helps the program easily tell where the block begins and ends. In many C-style languages, these
delimiters are curly braces:
1. if ( condition ) {
2. do something;
3. do something else;
4. }
In languages with delimiters it is often still common and recommended practice to indent the
statements within the block so that it is easier for a human to see where the block begins and ends
without having to scan for the braces.
In python, the interpreter can tell where the block begins and ends based on whitespace alone and
the delimiters are unnecessary:
1. if condition:
2. do something
3. do something else
This does mean that if you accidentally fail to indent a line that is meant to be in a block, it won't be
in that block. However, it ensures that the meaning and the whitespace are always consistent.
There are arguments to be made for and against significant whitespace, but most programming
languages have chosen not to go this route.
You’re going to have to change the number of spaces in front of one or more lines of code. It’s
is dedenting (or deindenting).
For example, if you want to move a print statement from the main part of the program into the
code block of a loop, you need to indent it. To move it out of the code block of a loop, you
need to deindent it. IDLE has tools to indent and dedent code blocks.
Indentation is meaningful to Python. You’ll get a syntax error if you have the wrong level of
indent.
It’s best to use four spaces of indent for each code block level. If you use another number of
spaces (2, 6, 8), that’s fine. The important thing is that all the code in the code block must
have the same number of spaces.
To go the other way, select the code and choose File → Dedent Region (or press Ctrl+[).
a. Imperatives:
b. Conditional sentences