Purpose of PEP-8 in Python

In this tutorial we will discuss the purpose of PEP-8 in python. PEP-8 can also be abbreviated as Python Enhancement proposal. It is a style guide which provides guidelines on how to write a python code that is easy to read.

Key benefits of PEP-8:

  • Improves readability
  • Reduce the errors
  • Increases the consistency

    Examples of PEP-8

Improving readability:

#Good
def calculate_sum(a, b):
return a + b
 
#Bad
def calculate_sum( a,b ):
return a+b

#Calling the function
result=calculate_sum( 3,4 )
print(result)
Output for both:
7

In the above written code, Both versions of the function when we called the arguments 3 and 4 returns 7. The only difference is that formatting and readability of the code, not in the execution or in the output.

 

Consistency:

#Good
import os
import sys

#Bad
import os,sys

#using the imported modules
print(os.name)
print(sys.version)
Output for both:
posix
3.9.7(default,Aug 31 2021, 13:28:12)

Each module must be imported in a separate line because it makes easy to manage and read the code. When both modules are imported in the same line using comma it makes the codes less easy to understand while dealing with many imports. Good version is preferred because it enhances the code readability and maintainability.

Encouraging best practices:

PEP-8 version helps us to improve the code quality by using simple variables in the code instead of using complex expressions.

#Good
def calculate_the_area_of_circle(radius):
PI=3.14
return PI*radius**2
#calling the function
result=calculate_the_area_of_circle(5)
print(result)

#bad
def cal_Area(r):
pi=3.14
return pi*r*r
#Calling the function
result=cal_Area(5)
print(result)
Output for both:
78.5

In the first scenario, the function name is more descriptive and follows the PEP-8 recommendation for function naming using lowercases separated by underscores. Whereas in the second scenario the function name is less descriptive which is difficult to understand to some users. parameter name “radius” is also descriptive when compared with second one “r”. Constant PI is indicated with capital letter in the first on which helps to understand that it is a constant value. Instead of using “r*r” like in second scenario we can use “radius**2” like in first one, which is more readable.

 

 

Leave a Comment

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

Scroll to Top