Proper indentation is crucial in Python to correctly structure and organize code. Unlike other programming languages that use brackets or keywords to denote code blocks, Python relies solely on indentation to delimit blocks of code. This means that the number of spaces used for indenting code matters in Python. Incorrect indentation can lead to IndentationErrors or unintended program behavior.
In this comprehensive guide, we will cover indentation rules and best practices specifically for code blocks within conditional statements in Python. Conditional statements like if
, elif
, else
, and while
statements contain indented blocks of code that only execute when certain conditions are met. Understanding how to correctly indent these conditional code blocks in Python is key to writing programs that run as expected.
Table of Contents
Open Table of Contents
Overview of Indentation in Python
Python uses indentation levels to create code blocks and group related statements together. This is a key component of Python’s syntax.
-
An indentation level in Python consists of 4 spaces. Never mix tabs and spaces.
-
Functions, loops, classes, conditionals, etc have colon (
:
) at the end of the starting line, followed by an indented block of code in the next line(s). -
To increase indentation, press Tab key or add 4 space characters.
-
To decrease indentation, press Shift+Tab or backspace 4 space characters.
-
All code at the same indentation level belongs to the same block.
-
Higher indentation levels are nested blocks inside parent blocks.
For example:
# Block 1
if condition:
# Block 2
do_something()
# Block 2
do_something_else()
# Block 1
do_something_after()
-
The
if
statement line ends with:
denoting the start of a new code block. -
The lines
do_something()
anddo_something_else()
are indented by 4 spaces, creating Block 2 nested under Block 1. -
do_something_after()
is at the same indentation as theif
statement, so it belongs to Block 1.
This structure will run do_something()
and do_something_else()
only when condition
is True, while do_something_after()
will run either way after the if statement block.
Indentation Rules for Conditional Statements
Conditional statements like if
, elif
, else
and while
have specific indentation rules in Python for the code blocks under them.
If Statements
The if
statement evaluates a condition and executes the indented code block below it if the condition is True.
if condition:
# execute code block
-
The
if
line ends with a colon:
and the code block is indented by 4 spaces under it. -
The block will execute only if
condition
has a True boolean value. -
Just the
if
line with no indented block below it will throw an error.
Incorrect indentation:
# Missing indented block
if condition:
print("Incorrectly indented if statement")
This will throw IndentationError: expected an indented block
because the print statement is not indented under the if
.
Correct indentation:
if condition:
print("Correctly indented block under if statement")
-
The print statement is indented by 4 spaces after the
if
line. -
This code block will run only when
condition
is True.
If/Else Statements
The else
can be paired with an if
statement to define an alternate block of code to run when the if
condition is False.
if condition:
# run if True
else:
# run if False
-
The
else
line starts at the same indentation level as theif
statement. -
The
else
code block is indented under it by 4 spaces. -
The
else
block runs only when theif
condition is False.
Incorrect indentation:
if condition:
print("Condition is True")
print("Outside if/else blocks")
else:
print("Condition is False")
This will throw an IndentationError
because the else
is not lined up with the if
properly.
Correct indentation:
if condition:
print("Condition is True")
else:
print("Condition is False")
print("Outside if/else blocks")
-
The
if
andelse
start on the same indentation level. -
The code blocks under them are indented by 4 spaces.
-
This ensures the
else
block runs at the right time.
Elif Statements
The elif
(short for else if) allows chaining multiple conditions to test.
if condition1:
# run if condition1 is True
elif condition2:
# run if condition1 is False and condition2 is True
else:
# run if both conditions are False
-
elif
lines start at the same indentation level as theif
andelse
statements. -
The code blocks below each
elif
is indented by 4 spaces. -
Python will test each
elif
condition in order if the previous conditions were False.
Incorrect indentation:
if condition1:
# do something
elif condition2:
# do something else
else:
# do another thing
This is incorrect because the elif
and else
blocks are not lined up properly with the initial if
statement.
Correct indentation:
if condition1:
# do something
elif condition2:
# do something else
else:
# do another thing
-
Now the
if
,elif
,else
all start at the same indentation level. -
The code blocks below them are indented correctly by 4 spaces.
-
This allows the
elif
andelse
blocks to run at the right times.
While Loops
The while
loop executes a code block repeatedly as long as a condition remains True.
while condition:
# execute loop body
-
The
while
line ends with a colon:
and the loop body is indented under it. -
The code block will run repeatedly as long as
condition
is True.
Incorrect indentation:
while condition:
print("Still in loop") # Loop body not indented
This will raise an IndentationError
because the print statement is not indented under the while
properly.
Correct indentation:
while condition:
print("Still in loop") # Loop body now indented
-
Loop body is indented 4 spaces under
while
-
The code will run repeatedly until condition becomes False
Try/Except Blocks
try
and except
blocks handle and catch exceptions in Python. The except
block must be indented properly to catch the exception from the try
.
try:
# run code
except:
# handle exception
- The
except
line should be lined up with thetry
statement. - The exception handling code goes in the indented block under the
except
.
Incorrect indentation
try:
# run code
except: # except not aligned with try
print("Caught exception")
This will not catch the exception properly because the except
is not aligned with the try
.
Correct indentation
try:
# run code
except: # except aligned with try
print("Caught exception")
- Now the
except
is indented correctly to catch any exceptions from thetry
block.
Indentation Best Practices
Beyond just following the indentation rules, here are some best practices for indentation in Python:
-
Be Consistent: Stick to 4 space indentations throughout the file. Never mix tabs and spaces.
-
Vertical Alignment: Visually align same-level blocks vertically using consistent indentation:
if condition1:
# indented 4 spaces
do_something()
elif condition2:
# align with if
do_something_else()
else:
# align else
final_thing()
-
Limit Line Length: Avoid having overly long lines of code. Break long lines logically based on coding style guides.
-
Use Blank Lines: Use blank lines between logical sections of code for better visual separation.
-
Comment Indentation: Comments should have the same indentation as next code block.
-
Tools: Use editors/IDEs that automatically indent to PEP 8 style guide. Most will also alert to indentation issues.
Common Indentation Errors
Some common indentation errors include:
-
Mixed tabs and spaces: Tabs indent to the next tab stop which may not match 4 spaces. Use only spaces.
-
Unbalanced indentation: Code blocks should have the same indentation levels.
-
Stray whitespace: Any unintended whitespace can shift code right messing up alignment.
-
Missing indented blocks: Forgetting to indent code under conditionals, loops, functions, etc.
-
Over-indenting: Indenting code levels too far right incorrectly.
-
Under-indenting: Not indenting levels enough relative to parent blocks.
Python will raise various errors like IndentationError
, TabError
, or SyntaxError
pointing to specific lines containing incorrect indentation.
Tools for Checking Indentation
Here are some useful tools for validating indentation:
-
IDEs: PyCharm, Visual Studio Code, etc. will auto-indent codes and flag issues in real-time.
-
pep8: PEP 8 style guide validation including flags for whitespace and indentation issues.
-
pycodestyle: Advanced style guide checker for Python code with customizable indentation rules.
-
pylint: Static code analysis looking for indentation inconsistencies and other issues.
-
black: Auto-formatter for Python that can fix some indentation issues automatically.
Conclusion
Proper indentation is critical for Python’s use of whitespace to structure code. Indenting conditional statements correctly ensures code blocks execute as expected.
Follow these key indentation rules and best practices for conditional statements:
-
Indent all code blocks by 4 spaces after
if
,elif
,else
,while
,try
etc. -
Align same-level conditional statements like
if
,elif
,else
vertically using consistent indentation. -
Indent nested code blocks another 4 spaces relative to parent indentation level.
-
Use blank lines and comments to separate logical sections of code.
-
Limit line length and be consistent with indentation across files.
-
Use tools like linters and auto-formatters to alert improper indentation issues.
Adhering to indentation rules and styles, especially for conditional statements, will help write Python code that executes reliably according to the expected program flow.