Understand PEP 8 Indentation and Line Length
Proper indentation and line length are fundamental to readable Python code. In this step, you will learn and apply the PEP 8 guidelines for these two aspects.
Indentation: PEP 8 recommends using 4 spaces per indentation level. This is a strong convention in the Python community.
Line Length: PEP 8 suggests limiting all lines to a maximum of 79 characters. For docstrings and comments, the limit is 72 characters. This improves readability, especially on smaller screens or when comparing code side-by-side.
Let's put this into practice. In the file explorer on the left, find and open the file indentation_example.py. The code inside demonstrates correct indentation for function definitions and multi-line statements.
## Correct indentation using 4 spaces.
def long_function_name(
var_one, var_two, var_three,
var_four):
print(var_one)
## Define some variables for demonstration.
var_one = "first"
var_two = "second"
var_three = "third"
var_four = "fourth"
## Aligning with the opening delimiter.
foo = long_function_name(var_one, var_two,
var_three, var_four)
## Using a hanging indent. The first line has no arguments,
## and subsequent lines are indented to distinguish them.
bar = long_function_name(
var_one, var_two,
var_three, var_four)
## A multi-line list.
my_list = [
1, 2, 3,
4, 5, 6,
]
## Calling the functions to produce output.
long_function_name("first call", "second", "third", "fourth")
foo = long_function_name("second call", "second", "third", "fourth")
bar = long_function_name("third call", "second", "third", "fourth")
After reviewing the code, run the script to see its output. Open the terminal at the bottom of the WebIDE and execute the following command:
python ~/project/indentation_example.py
The script will run and print the first argument from each function call. The output will be:
first call
second call
third call
This exercise demonstrates how consistent indentation makes complex function calls and data structures much easier to read.