Join Digital Marketing Foundation MasterClass worth Rs 1999 FREE

Beginners Guide to Write Beautiful Python Code With PEP 8

08 6a10516e3b48f9cb4257675bd3e8d396 1

PEP is a document that contains best practices and python code writing guidelines. The primary focus of the documentation is to improve the consistency and readability of the Python code, written by Guido Van Rossum, Nick Coghlan, and Barry Warsaw.

PEP or Python Enhancement Proposal is used to define new features such as Python’s style and design. But we need a PEP, is the question?

PEP 8’s basic goal is to improve the readability of the code. As said by Guido Van Rossum himself, code is read more frequently than written. This is because it will only be written once, no matter how long you have spent writing the script.

It’s not the same for reading the script. A code can be read by the writer or some other developer multiple times. Therefore, you have to be able to understand why it works and what it does every time you look at that code.

If you follow the guidelines listed in PEP 8, you would have named the variables correctly and added white space, you can follow the logic in the code.

To make it easier to read, you should also put comments on your script. Also, after PEP 8 becomes more critical when you’re looking for a job as a designer.

Want to Know the Path to Become a Data Science Expert?

Download Detailed Brochure and Get Complimentary access to Live Online Demo Class with Industry Expert.

Date: March 30 (Sat) | 11 AM - 12 PM (IST)
This field is for validation purposes and should be left unchanged.

Let’s explore in detail all the features of the PEP 8 documentation that makes code easier to read:

Naming Conventions

When you are coding, there are several things that you have to give a name to like variables, classes, functions, packages, etc. So, to save time and energy for the future, you need to select names that make sense. Meaning that you should be able to figure out what is in the variable by just seeing its name. Using inappropriate names will only increase your problems during debugging.

Naming conventions
Naming conventions source – slideshare

Here is the list of the common naming styles that you should use while coding in Python:

Variable – a single letter, a word or multiple words separated by an underscore, all in lowercase. For example var, the_variable.

Function – Use words or multiple words separated by underscores, all in lowercase. For example func, the_function.

Constant – Use a single letter, word, or multiple words separated by underscores, all in uppercase. For example, CONST, THE_CONSTANT.

Method – Use a single word or multiple words separated by underscores, all in lowercase. For example, method, the_method.

Class – A single word or multiple words without underscores separating them. The first letter should be capitalized. This format f word is known as camel case. For example, Model, MyClass.

Module – A short word or multiple words separated by underscores, all in lowercase. For example module_example.py.

Package – A short word or words not separated by underscore, all in lowercase. For example packageexample.

Now when it comes to naming conventions, just selecting the right format is not enough. You also have to select the right name. Here are a few tips that will help you name effectively:

Before you give a name to your variable, function, method, or class, you need to make sure that it makes your code readable. What you need to do is think of descriptive names that clearly show what the object represents.

Let’s start with variables. It is a very common mistake among beginners to use a single-letter name for variable like x or y. But x doesn’t give an idea of what it represents. The issue with that is depicted in the following example:

>>>

>>> # Not recommended

>>> x = 'John Smith'

>>> y, z = x.split()

>>> print(z, y, sep=', ')

'Smith, John'

Now, this will only work when you the exact idea of what x, y, and z is. This will become much more confusing when you are working on complicated projects where there are thousands of variables or you are working with other developers. Here is an example with a clear choice of names for variables:

>>>

>>> # Recommended

>>> name = 'John Smith'

>>> first_name, last_name = name.split()

>>> print(last_name, first_name, sep=', ')

'Smith, John'

This will increase the amount of time you spend on typing, but the overall advantage it provides by offering readability makes up for it. Also, you must avoid using abbreviations while naming objects in your code. Here is an example where db() is a function that takes x, a single argument, and doubles it:

# Not recommended

def db(x):

    return x * 2

You might think that using db as an abbreviation for double is a sensible choice. But if you come back to this code after a few days, you might forget how you abbreviated it making the code difficult to understand. Now, if you use the following example, you will be able to get a clearer idea of what a function does even if you check out the code in a couple of weeks or months:

# Recommended

def multiply_by_two(x):

    return x * 2

The same thing can be applied to all the other objects and data types involved in Python. You must use descriptive names.

Code Layout

Another major aspect of code’s readability is code layout. Here you will learn about adding vertical whitespace for improving readability of the code. 

Blank Lines

Blank lines or vertical whitespace plays an important role for improving the code’s readability. If your code is bunched up, it can get overwhelming making it hard to read. Also, if you add too much whitespace, it will make the code look sparse and the reader will have to scroll down unnecessarily.

Black lines
Black lines source – slideshare

Here are three guidelines that will help you understand how to use blank lines or vertical whitespace properly:

Using two blank lines for classes and top-level functions

It is important that you self-contained the top-level classes and functions and handle their functionality separately. Vertical space around them can help in clearing their boundaries. Take a look at this example:

class MyFirstClass:

    pass

class MySecondClass:

    pass

def top_level_function():

    return None

Using a single blank line for surrounding method definitions present inside classes

All the functions present in the class are in relation with one another. So, you need to leave just a single line between them:

class MyClass:

    def first_method(self):

        return None

    def second_method(self):

        return None

Using blank lines inside functions for clearing the steps

A complicated function might have several steps involved before reaching the return statement. For helping the readers better understand the function’s logic, you need to leave a blank line after every step. Here is an example where a function is used for calculating the list’s variance. There is a blank line between the two steps of the functions and before the return statement:

def calculate_variance(number_list):

    sum_list = 0

    for number in number_list:

        sum_list = sum_list + number

    mean = sum_list / len(number_list)

    sum_squares = 0

    for number in number_list:

        sum_squares = sum_squares + number**2

    mean_squares = sum_squares / len(number_list)

    return mean_squares - mean**2

Blank lines or vertical whitespace can help the readers understand how and where the code is splitting into different sections and how one section is related to other.

Maximum Line Length and Line Breaking

According to PEP 8, the limit for a line is 79 characters. This allows you to avoid line wrapping and have multiple files open next to each other. However, it is not always possible to keep the statements under 79 characters. PEP 8 contains ways that allow the statements to run for multiple lines. If parentheses, braces, or brackets are used in the code, line continuation will be assumed by Python. Take a look at the below example:

def function(arg_one, arg_two,

             arg_three, arg_four):

    return arg_one

If you cannot get implied continuation, you can break lines by using backslashes:

from mypkg import example1, \

    example2, example3

If implied continuation is not working for you and you have use line breaking, you need to make sure that you break the line before the binary operators. Here is an example of breaking the line before the binary operator:

# Recommended

total = (first_variable

         + second_variable

         - third_variable)

It is very clear to see which variable is added or subtracted. Here is another example where the line is broke after the binary operator:

# Not Recommended

total = (first_variable +

         second_variable -

         third_variable)

It is difficult to see which variable is added or subtracted.

Indentation

Also known as leading whitespace, Indentation plays an important role making the code readable. The indentation shows how different statements in the code are grouped together. Consider this:

x = 3

if x > 5:

    print(‘x is larger than 5’)

The print statement is indented which shows that it should be executed only if the if condition is true. Indentation also shows what code belongs to which class and what code should be executed when a function is called. Here are the PEP 8’s key indentation rules:

  • Use spaces instead of tabs
  • 4 consecutive spaces for indentation

If you are using both spaces and tabs for indentation, you will have errors. To check for consistency you have to run the code with a –t flag. If there is an inconsistency with spaces and tabs, issue warnings will be given by the interpreter:

$ python2 -t code.py

code.py: inconsistent use of tabs and spaces in indentation

If you want to know exactly where the inconsistency is, you need to use the –tt flag that issues errors, not warnings:

$ python2 -tt code.py

  File "code.py", line 3

    print(i, j)

             ^

TabError: inconsistent use of tabs and spaces in indentation

If you are working on Python3, all the issues regarding inconsistencies in spaces and tabs are automatically issues:

$ python3 code.py

  File "code.py", line 3

    print(i, j)

              ^

TabError: inconsistent use of tabs and spaces in indentation

Indentation Following Line Breaks

You have to use indentation when you are breaking lines for keeping the statements under 79 characters. This will help the reader in distinguishing between a single line of code and two lines of code. There are two indentation styles that you can use:

Aligning the block with opening delimiter

def function(arg_one, arg_two,

             arg_three, arg_four):

    return arg_one

You need 4 spaces for aligning the code with the opening delimiter. Now, the if statement has a nested code block, indentation can be a little trick. Take a look at the following example:

x = 5

if (x > 3 and

    x < 10):

    print(x)

For solving this, PEP 8 offers two alternatives:

After the final condition, add a comment. This will separate it from the nested code due to the option in syntax highlighting available in most editors:

x = 5

if (x > 3 and

    x < 10):

    # Both conditions satisfied

    print(x)

On the line continuation, add an extra indentation:

x = 5

if (x > 3 and

        x < 10):

    print(x)

Hanging Indent is another style of indentation. In this, every line of the block is indented, except the first. In this, there must not be any arguments on the first line. Here is an example:

var = function(

    arg_one, arg_two,

    arg_three, arg_four)

# Not Recommended

var = function(arg_one, arg_two,

    arg_three, arg_four)

When you are working on hanging indent and want to distinguish between the continued line inside the function, you need to add an extra indentation. In the following example, the indentation level of the code and the continued lines is the same which makes it difficult to read:

# Not Recommended

def function(

    arg_one, arg_two,

    arg_three, arg_four):

    return arg_one

Now, if you use double indentation for the continuous lines it will help you distinguish between the function’s body and arguments:

def function(

        arg_one, arg_two,

        arg_three, arg_four):

    return arg_one

Where to Put the Closing Brace

When you are working with line continuations, it is easy to forget about the closing parenthesis, braces, or brackets. There are two options provided by PEP 8 for the closing brace of the line continuations:

Use the first non-whitespace character for lining up the closing brace with the previous line:

list_of_numbers = [

    1, 2, 3,

    4, 5, 6,

    7, 8, 9

    ]

Use the first character of the line for lining up the closing brace.

list_of_numbers = [

    1, 2, 3,

    4, 5, 6,

    7, 8, 9

]

Comments

Once you have written the code, you need to add a comment to the document. It is important because it helps the future you and any other collaborators to understand your code. When you are adding comments, you need to remember the following key points:

  • Using complete sentences with first word starting with an uppercase.
  • Limiting the comment’s length to 72 characters.
  • Updating the comments when you make changes to the code.

Block Comments

For documenting a small section of code, you should use block comments. They are especially beneficial when you perform a single action by writing multiple lines of code like updating an entry of database or importing data from a file. Here are a few rules for writing block comments according to the PEP 8 documentation:

  • Using a # followed by a space for starting each line.
  • Using a single # for separating paragraphs by a line.
  • Indenting the block comments the same as the code.

Take a look at the following example where a block comment is used to explain the for loop:

for i in range(0, 10):

    # Loop over i ten times and print out the value of i, followed by a

    # new line character

    print(i, '\n')

If the code is complicated, you might have to enter more than one paragraph in the block comment:

def quadratic(a, b, c, x):

    # Calculate the solution to a quadratic equation using the quadratic

    # formula.

    #

    # There are always two solutions to a quadratic equation, x_1 and x_2.

    x_1 = (- b+(b**2-4*a*c)**(1/2)) / (2*a)

    x_2 = (- b-(b**2-4*a*c)**(1/2)) / (2*a)

    return x_1, x_2

Inline Comments

These types of comments are used for explaining a single statement is a code. Here are the guidelines laid down in PEP 8 for inline comments:

  1. The inline comments must be used sparingly.
  2. They must be written on the same line as the line of code they are referring to.
  3. Use more than 2 spaces for separating the inline comments from the statement.
  4. Use a # and a single space for starting the inline comments.

Here is an example of an inline comment.

x = 5  # This is an inline comment

Documentation Strings

Enclosed in single or double quotation marks, documentation strings are present on the first line of any function, method, class, or module. They are used for explaining and documenting a block of code. Here are the rules for applying document strings to the code:

  • The correct way to use quotation on document string is “””This is a docstring”””.
  • They must be mentioned for all public functions, classes, modules, and methods.
  • Add “”” to the end of a multi line docstring.

Here is an example that will help you understand the usage of documentation strings better:

def quadratic(a, b, c, x):

    """Solve quadratic equation via the quadratic formula.

    A quadratic equation has the following form:

    ax**2 + bx + c = 0

    There are always two solutions to a quadratic equation: x_1 & x_2.

    """

    x_1 = (- b+(b**2-4*a*c)**(1/2)) / (2*a)

    x_2 = (- b-(b**2-4*a*c)**(1/2)) / (2*a)

    return x_1, x_2

You need to keep the “”” on the same line for one-line docstrings:

def quadratic(a, b, c, x):

    """Use the quadratic formula"""

    x_1 = (- b+(b**2-4*a*c)**(1/2)) / (2*a)

    x_2 = (- b-(b**2-4*a*c)**(1/2)) / (2*a)

    return x_1, x_2

Whitespace in Expressions and Statements

Whitespace in expressions and statements
Whitespace in expressions and statements source – slideshare

You have to use whitespace in expressions and statements to make the code readable. But you have to be very careful with it as too much whitespace will make combining related terms difficult and too little whitespace will make the code difficult to read. 

Whitespace Around Binary Operators

When you are using binary operators, you need to use a single space on both sides. When you are assigning a value to the argument of the function, you don’t have to use spaces:

# Recommended

def function(default_parameter=5):

    # …

# Not recommended

def function(default_parameter = 5):

    # …

When there are more than one operator, you should use the whitespace around the operator that has lowest priority:

# Recommended

y = x**2 + 5

z = (x+y) * (xy)

# Not Recommended

y = x ** 2 + 5

z = (x + y) * (x y)

When you are working with slices, colons are like the binary operators. So the same rule applies to them:

list[3:4]

# Treat the colon as the operator with lowest priority

list[x+1 : x+2]

# In an extended slice, both colons must be

# surrounded by the same amount of whitespace

list[3:4:5]

list[x+1 : x+2 : x+3]

# The space is omitted if a slice parameter is omitted

list[x+1 : x+2 :]

When to Avoid Adding Whitespace

In some cases, the addition of whitespace can make the code difficult to read by making it sparse. So there are some places outlined by PEP 8 where you should avoid using whitespace. The end of the line is one such place. Known as trailing whitespace, it cannot be seen and can create errors that cannot be traced. Here is a list outlining some other cases where you should not use whitespace:

  1. Inside parentheses, braces, or brackets:
# Recommended

my_list = [1, 2, 3]

# Not recommended

my_list = [ 1, 2, 3, ]
  1. Before a colon, semicolon, or comma:
x = 5

y = 6

# Recommended

print(x, y)

# Not recommended

print(x , y)
  1. Before the open parenthesis where the function’s arguments start:
def double(x):

    return x * 2

# Recommended

double(3)

# Not recommended

double (3)
  1. Before the open bracket starting a slice or an index:
# Recommended

list[3]

# Not recommended

list [3]
  1. Between a closing parenthesis and a trailing comma:
# Recommended

tuple = (1,)

# Not recommended

tuple = (1, )
  1. For aligning the assignment operators:
# Recommended

var1 = 5

var2 = 6

some_long_var = 7

# Not recommended

var1          = 5

var2          = 6

some_long_var = 7

Programming Recommendations

This section will cover the suggestions provided by PEP 8 for preserving consistency and removing ambiguity.

  1. Don’t use the equivalence operator for comparing Boolean values to true or false.
  2. Empty sequence in if statements are false.
  3. In the if statements, instead of ‘not’, use ‘is not’.
  4. If x is not None, do not use if x:.
  5. Instead of slicing, try using .startswith() and .endswith().

Ignoring PEP 8

PEP 8 helps you in creating a clean, readable, and professional code. So, you should never ignore PEP 8. However, you can avoid PEP 8, if it is causing inconvenience in the following cases:

  • Compliance with PEP 8 breaks compatibility with the software.
  • The code you are working with doesn’t comply with PEP 8.
  • You have to make the code compatible with Python’s older versions.

Ensuring the Code Follows PEP 8

Ensuring the code follows pep 8
Ensuring the code follows pep 8 source – youtube

You might not remember all the rules mentioned in the PEP 8 documentation. To speed up the process of making your code compiled with PEP 8, you can take the help of few tools including the following:

1. Linters

These are used for analyzing code and flagging errors. They also show suggestions for fixing the error. You can add them as extensions to the editor. The pycodestyle linter checks the code for style conventions mentioned in PEP 8. Flake8 is another linter tool with capabilities of debugger, pycodestyle, and pyflakes.

2. Autoformatters

These programs are used for automatically refactoring the code to conform to the conventions of PEP 8. Black is one such program.

At times these guidelines can feel pedantic, but you need to remember that they help in improving your code so that your collaborators or potential employers can understand the code. It makes the code readable and of high-quality.

Final Thoughts

You can become a highly qualified Python programmer by taking Python programming CourseAny aspiring programmer can learn from the fundamentals of Python and continue to finesse Python after the course.

Avatar of niharika mahendra
Niharika Mahendra
An enthusiastic Content Writer & Marketer with 2 years of expertise in writing & curating Digital Marketing content. She is well-versed in writing website content, blogs, white papers, business collaterals, case studies & digital marketing content. She is passionate about Digital Marketing which keeps her updated with all the recent updates and trends of Digital Marketing.

Leave a Comment

Your email address will not be published. Required fields are marked *

In-Demand Courses

4-7 months Instructor Led Live Online Training
Starts March 30, 31, 1, 2, 2024
  • Covers all Digital Marketing Techniques

4 months Online
New Batch Dates are not Open
  • Digital Media Mastery (with Paid Media Expertise)
Digital Marketing Webinars
Mar 30
Upcoming
Raj Sharma, Digital Vidya Team 11:00 AM - 12:00 PM (IST)
Apr 28
Completed
Marketing Leaders from Paytm Insider, Cognizant and Digital Vidya 03:00 PM - 04:00 PM (IST)
Mar 24
Completed
Marketing Leaders from Merkle Sokrati, 3M, Uber India and VIP Industries Limited 03:00 PM - 04:00 PM (IST)

Discuss With A Career Advisor

Not Sure, What to learn and how it will help you?

Call Us Live Chat Free MasterClass
Scroll to Top