Code icon

The App is Under a Quick Maintenance

We apologize for the inconvenience. Please come back later

Menu iconMenu iconPython Programming Unlocked for Beginners
Python Programming Unlocked for Beginners

Chapter 10: Python Best Practices

10.1 PEP 8 - Style Guide for Python Code

As we approach the end of this book, it is important to note that the best practices for Python programmers are critical to the success of any project. While there are many best practices that programmers can follow, the ones presented here are essential to maintaining efficient, readable, and maintainable code. In this chapter, we will delve deeper into PEP 8, the official style guide for Python code, and explore how it can be used to improve your code. 

Furthermore, we will discuss other critical topics such as code organization, documentation, and testing. It is essential to understand these concepts in their entirety, as they will be crucial in ensuring that your Python projects are a success.

PEP 8 is the Python Enhancement Proposal that provides a set of guidelines and conventions for writing Python code. The primary purpose of PEP 8 is to make the code more readable and maintainable by providing a consistent style. Although PEP 8 is not a strict requirement, it is highly recommended to follow these guidelines to ensure that your code is easily understood by others, and even by yourself, in the future. 

Some of the key aspects of PEP 8 include:

10.1.1: Indentation:

When writing code, it is important to maintain consistent formatting. This can be achieved by using 4 spaces per indentation level, rather than mixing spaces and tabs. By doing so, the code becomes more readable and easier to understand for others who may need to work with the code in the future. Additionally, consistent formatting can help prevent errors and make debugging easier. Therefore, it is highly recommended to use 4 spaces per indentation level for all code you write.

Example:

# Good
def my_function(arg1, arg2):
    result = arg1 + arg2
    return result

# Bad
def my_function(arg1, arg2):
  result = arg1 + arg2
  return result 

10.1.2: Maximum Line Length: 

One way to improve code readability is to limit the number of characters per line. This can be achieved by setting a maximum line length of 79 characters. By doing this, the code becomes easier to read, especially when working with multiple files side by side. It allows for a more organized and structured codebase, as developers can quickly scan through the code and identify potential issues or areas for improvement.

Additionally, keeping the code within a certain length limit can also help with debugging and testing, as it minimizes the need for horizontal scrolling and makes it easier to spot errors.

Example:

# Good
def my_function(long_arg1, long_arg2,
                long_arg3, long_arg4):
    result = (
        long_arg1 + long_arg2
        - long_arg3 * long_arg4
    )
    return result

# Bad
def my_function(long_arg1, long_arg2, long_arg3, long_arg4): result = long_arg1 + long_arg2 - long_arg3 * long_arg4; return result

10.1.3: Imports:

When writing code, it is important to organize your imports in a clear and consistent manner. By placing your imports at the top of the file, you can make it easier for other developers to understand what external dependencies your code relies on. However, it's not enough to simply list your imports in a random order. To maximize readability, imports should be separated by a blank line, and organized in a specific order.

First, you should list any standard library imports that your code requires. These are built-in modules that come with the Python language, such as "os" or "sys".

Next, you should list any third-party imports that your code requires. These are external modules that you have installed using a package manager like "pip". Examples of third-party modules might include "numpy" or "pandas".

Finally, you should list any local application or library-specific imports that your code requires. These are modules that you have written yourself, or that are specific to your particular project.

By following this organization scheme, you can help ensure that your code is easy to read and understand, even for developers who are unfamiliar with your project. So don't forget to take a little extra time to organize your imports properly!

Example

# Good
import os
import sys

import requests

from my_module import my_function

# Bad
import os, sys
from my_module import my_function
import requests

10.1.4: Whitespace:

When writing code, it is important to use whitespace effectively. This means that while you should avoid using excessive whitespace, you should also use it to separate logical sections of your code. For example, you can use a single blank line to separate functions, methods, or class definitions. By using whitespace in this way, you can make your code more organized and easier to read.

In addition to separating code sections, it is also important to use whitespace around operators and after commas in lists, tuples, or dictionaries. This makes the code more readable and easier to understand, especially if someone else needs to review or modify it in the future.

Example

# Good
my_list = [1, 2, 3, 4]
result = x * y + z

# Bad
my_list=[1,2,3,4]
result=x*y+z

10.1.5: Naming Conventions:

  • Variables and function names should be lowercase, with words separated by underscores (e.g., my_variablemy_function).
  • Constants should be in uppercase, with words separated by underscores (e.g., MY_CONSTANT).
  • Class names should use the CapWords (PascalCase) convention (e.g., MyClass).
  • Method names should be lowercase, with words separated by underscores (e.g., my_method).

Example

# Good
class MyClass:
    my_variable = 10

    def my_method(self):
        pass

# Bad
class myclass:
    MyVariable = 10

    def MyMethod(self):
        pass

10.1.6: Comments:

When writing code, it is important to use comments to explain the purpose of the code, especially when it might be difficult to understand. Comments help other programmers who may need to work with your code to understand how it works and what it does.

It is recommended to use inline comments sparingly, as adding too many comments can make the code harder to read. When adding inline comments, it is important to separate them from the code with at least two spaces.

Always start comments with a capital letter and end with a period. This helps to maintain consistency and readability within your code, and can make it easier for others to understand what you are trying to accomplish.

In summary, comments are a vital part of writing good code, and can help to make your code more understandable and maintainable. So don't forget to add comments to your code!

Example

# Good
def my_function():
    # Calculate the result based on some logic.
    result = 42
    return result

# Bad
def my_function():
    result = 42  # Calculate the result based on some logic.
    return result

10.1.7: Docstrings:

Using docstrings, or triple-quoted strings, is a great way to provide documentation for your modules, classes, functions, and methods. This can help others understand the purpose and usage of your code more effectively, which can be especially important when working on projects with others or contributing to open-source projects.

Not only can good documentation make it easier for others to use and build on your code, but it can also make it easier for you to come back to your own code later on and remember how it works. In fact, many developers consider good documentation to be just as important as good code itself, since it can help ensure that your code is maintainable and usable in the long run. So, if you're not already using docstrings in your code, it might be worth taking the time to start incorporating them into your programming practices.

Example

# Good
def my_function(arg1, arg2):
    """
    Calculate the sum of two arguments.

    Args:
        arg1 (int): The first argument.
        arg2 (int): The second argument.

    Returns:
        int: The sum of the two arguments.
    """
    return arg1 + arg2

# Bad
def my_function(arg1, arg2):
    # Calculate the sum of two arguments
    return arg1 + arg2

These are just a few of the many guidelines provided by PEP 8. It is recommended to read the full PEP 8 document (https://www.python.org/dev/peps/pep-0008/) to familiarize yourself with all the guidelines and apply them consistently in your Python projects.

Exercise 10.1.1: PEP 8 Indentation

In this exercise, you'll practice fixing the indentation in a Python script to follow the PEP 8 guidelines.

Instructions:
Fix the indentation in the given Python script. The script should have 4 spaces for each indentation level.

Solution:

def my_function(arg1, arg2):
    result = arg1 + arg2
    return result

if __name__ == "__main__":
    num1 = 5
    num2 = 10
    sum_result = my_function(num1, num2)
    print(f"The sum of {num1} and {num2} is {sum_result}.")

Output:

The sum of 5 and 10 is 15.

Exercise 10.1.2: PEP 8 Imports

In this exercise, you'll practice organizing imports according to PEP 8 guidelines.

Instructions:
Reorganize the given imports in the Python script so that they follow the PEP 8 guidelines.

Solution:

import os
import sys

import requests

from my_module import my_function

print("Imports organized according to PEP 8.")

Output:

Imports organized according to PEP 8.

Note: The output will differ based on your system and the actual "my_module" you import.

Exercise 10.1.3: PEP 8 Naming Conventions

In this exercise, you'll practice applying PEP 8 naming conventions to a Python script.

Instructions:
Update the given Python script so that it follows the PEP 8 naming conventions for variables, functions, and classes.

Solution:

class MyClass:
    my_variable = 10

    def my_method(self):
        return self.my_variable * 2

def main():
    my_instance = MyClass()
    result = my_instance.my_method()
    print(f"The result is: {result}")

if __name__ == "__main__":
    main()

Output:

The result is: 20

10.1 PEP 8 - Style Guide for Python Code

As we approach the end of this book, it is important to note that the best practices for Python programmers are critical to the success of any project. While there are many best practices that programmers can follow, the ones presented here are essential to maintaining efficient, readable, and maintainable code. In this chapter, we will delve deeper into PEP 8, the official style guide for Python code, and explore how it can be used to improve your code. 

Furthermore, we will discuss other critical topics such as code organization, documentation, and testing. It is essential to understand these concepts in their entirety, as they will be crucial in ensuring that your Python projects are a success.

PEP 8 is the Python Enhancement Proposal that provides a set of guidelines and conventions for writing Python code. The primary purpose of PEP 8 is to make the code more readable and maintainable by providing a consistent style. Although PEP 8 is not a strict requirement, it is highly recommended to follow these guidelines to ensure that your code is easily understood by others, and even by yourself, in the future. 

Some of the key aspects of PEP 8 include:

10.1.1: Indentation:

When writing code, it is important to maintain consistent formatting. This can be achieved by using 4 spaces per indentation level, rather than mixing spaces and tabs. By doing so, the code becomes more readable and easier to understand for others who may need to work with the code in the future. Additionally, consistent formatting can help prevent errors and make debugging easier. Therefore, it is highly recommended to use 4 spaces per indentation level for all code you write.

Example:

# Good
def my_function(arg1, arg2):
    result = arg1 + arg2
    return result

# Bad
def my_function(arg1, arg2):
  result = arg1 + arg2
  return result 

10.1.2: Maximum Line Length: 

One way to improve code readability is to limit the number of characters per line. This can be achieved by setting a maximum line length of 79 characters. By doing this, the code becomes easier to read, especially when working with multiple files side by side. It allows for a more organized and structured codebase, as developers can quickly scan through the code and identify potential issues or areas for improvement.

Additionally, keeping the code within a certain length limit can also help with debugging and testing, as it minimizes the need for horizontal scrolling and makes it easier to spot errors.

Example:

# Good
def my_function(long_arg1, long_arg2,
                long_arg3, long_arg4):
    result = (
        long_arg1 + long_arg2
        - long_arg3 * long_arg4
    )
    return result

# Bad
def my_function(long_arg1, long_arg2, long_arg3, long_arg4): result = long_arg1 + long_arg2 - long_arg3 * long_arg4; return result

10.1.3: Imports:

When writing code, it is important to organize your imports in a clear and consistent manner. By placing your imports at the top of the file, you can make it easier for other developers to understand what external dependencies your code relies on. However, it's not enough to simply list your imports in a random order. To maximize readability, imports should be separated by a blank line, and organized in a specific order.

First, you should list any standard library imports that your code requires. These are built-in modules that come with the Python language, such as "os" or "sys".

Next, you should list any third-party imports that your code requires. These are external modules that you have installed using a package manager like "pip". Examples of third-party modules might include "numpy" or "pandas".

Finally, you should list any local application or library-specific imports that your code requires. These are modules that you have written yourself, or that are specific to your particular project.

By following this organization scheme, you can help ensure that your code is easy to read and understand, even for developers who are unfamiliar with your project. So don't forget to take a little extra time to organize your imports properly!

Example

# Good
import os
import sys

import requests

from my_module import my_function

# Bad
import os, sys
from my_module import my_function
import requests

10.1.4: Whitespace:

When writing code, it is important to use whitespace effectively. This means that while you should avoid using excessive whitespace, you should also use it to separate logical sections of your code. For example, you can use a single blank line to separate functions, methods, or class definitions. By using whitespace in this way, you can make your code more organized and easier to read.

In addition to separating code sections, it is also important to use whitespace around operators and after commas in lists, tuples, or dictionaries. This makes the code more readable and easier to understand, especially if someone else needs to review or modify it in the future.

Example

# Good
my_list = [1, 2, 3, 4]
result = x * y + z

# Bad
my_list=[1,2,3,4]
result=x*y+z

10.1.5: Naming Conventions:

  • Variables and function names should be lowercase, with words separated by underscores (e.g., my_variablemy_function).
  • Constants should be in uppercase, with words separated by underscores (e.g., MY_CONSTANT).
  • Class names should use the CapWords (PascalCase) convention (e.g., MyClass).
  • Method names should be lowercase, with words separated by underscores (e.g., my_method).

Example

# Good
class MyClass:
    my_variable = 10

    def my_method(self):
        pass

# Bad
class myclass:
    MyVariable = 10

    def MyMethod(self):
        pass

10.1.6: Comments:

When writing code, it is important to use comments to explain the purpose of the code, especially when it might be difficult to understand. Comments help other programmers who may need to work with your code to understand how it works and what it does.

It is recommended to use inline comments sparingly, as adding too many comments can make the code harder to read. When adding inline comments, it is important to separate them from the code with at least two spaces.

Always start comments with a capital letter and end with a period. This helps to maintain consistency and readability within your code, and can make it easier for others to understand what you are trying to accomplish.

In summary, comments are a vital part of writing good code, and can help to make your code more understandable and maintainable. So don't forget to add comments to your code!

Example

# Good
def my_function():
    # Calculate the result based on some logic.
    result = 42
    return result

# Bad
def my_function():
    result = 42  # Calculate the result based on some logic.
    return result

10.1.7: Docstrings:

Using docstrings, or triple-quoted strings, is a great way to provide documentation for your modules, classes, functions, and methods. This can help others understand the purpose and usage of your code more effectively, which can be especially important when working on projects with others or contributing to open-source projects.

Not only can good documentation make it easier for others to use and build on your code, but it can also make it easier for you to come back to your own code later on and remember how it works. In fact, many developers consider good documentation to be just as important as good code itself, since it can help ensure that your code is maintainable and usable in the long run. So, if you're not already using docstrings in your code, it might be worth taking the time to start incorporating them into your programming practices.

Example

# Good
def my_function(arg1, arg2):
    """
    Calculate the sum of two arguments.

    Args:
        arg1 (int): The first argument.
        arg2 (int): The second argument.

    Returns:
        int: The sum of the two arguments.
    """
    return arg1 + arg2

# Bad
def my_function(arg1, arg2):
    # Calculate the sum of two arguments
    return arg1 + arg2

These are just a few of the many guidelines provided by PEP 8. It is recommended to read the full PEP 8 document (https://www.python.org/dev/peps/pep-0008/) to familiarize yourself with all the guidelines and apply them consistently in your Python projects.

Exercise 10.1.1: PEP 8 Indentation

In this exercise, you'll practice fixing the indentation in a Python script to follow the PEP 8 guidelines.

Instructions:
Fix the indentation in the given Python script. The script should have 4 spaces for each indentation level.

Solution:

def my_function(arg1, arg2):
    result = arg1 + arg2
    return result

if __name__ == "__main__":
    num1 = 5
    num2 = 10
    sum_result = my_function(num1, num2)
    print(f"The sum of {num1} and {num2} is {sum_result}.")

Output:

The sum of 5 and 10 is 15.

Exercise 10.1.2: PEP 8 Imports

In this exercise, you'll practice organizing imports according to PEP 8 guidelines.

Instructions:
Reorganize the given imports in the Python script so that they follow the PEP 8 guidelines.

Solution:

import os
import sys

import requests

from my_module import my_function

print("Imports organized according to PEP 8.")

Output:

Imports organized according to PEP 8.

Note: The output will differ based on your system and the actual "my_module" you import.

Exercise 10.1.3: PEP 8 Naming Conventions

In this exercise, you'll practice applying PEP 8 naming conventions to a Python script.

Instructions:
Update the given Python script so that it follows the PEP 8 naming conventions for variables, functions, and classes.

Solution:

class MyClass:
    my_variable = 10

    def my_method(self):
        return self.my_variable * 2

def main():
    my_instance = MyClass()
    result = my_instance.my_method()
    print(f"The result is: {result}")

if __name__ == "__main__":
    main()

Output:

The result is: 20

10.1 PEP 8 - Style Guide for Python Code

As we approach the end of this book, it is important to note that the best practices for Python programmers are critical to the success of any project. While there are many best practices that programmers can follow, the ones presented here are essential to maintaining efficient, readable, and maintainable code. In this chapter, we will delve deeper into PEP 8, the official style guide for Python code, and explore how it can be used to improve your code. 

Furthermore, we will discuss other critical topics such as code organization, documentation, and testing. It is essential to understand these concepts in their entirety, as they will be crucial in ensuring that your Python projects are a success.

PEP 8 is the Python Enhancement Proposal that provides a set of guidelines and conventions for writing Python code. The primary purpose of PEP 8 is to make the code more readable and maintainable by providing a consistent style. Although PEP 8 is not a strict requirement, it is highly recommended to follow these guidelines to ensure that your code is easily understood by others, and even by yourself, in the future. 

Some of the key aspects of PEP 8 include:

10.1.1: Indentation:

When writing code, it is important to maintain consistent formatting. This can be achieved by using 4 spaces per indentation level, rather than mixing spaces and tabs. By doing so, the code becomes more readable and easier to understand for others who may need to work with the code in the future. Additionally, consistent formatting can help prevent errors and make debugging easier. Therefore, it is highly recommended to use 4 spaces per indentation level for all code you write.

Example:

# Good
def my_function(arg1, arg2):
    result = arg1 + arg2
    return result

# Bad
def my_function(arg1, arg2):
  result = arg1 + arg2
  return result 

10.1.2: Maximum Line Length: 

One way to improve code readability is to limit the number of characters per line. This can be achieved by setting a maximum line length of 79 characters. By doing this, the code becomes easier to read, especially when working with multiple files side by side. It allows for a more organized and structured codebase, as developers can quickly scan through the code and identify potential issues or areas for improvement.

Additionally, keeping the code within a certain length limit can also help with debugging and testing, as it minimizes the need for horizontal scrolling and makes it easier to spot errors.

Example:

# Good
def my_function(long_arg1, long_arg2,
                long_arg3, long_arg4):
    result = (
        long_arg1 + long_arg2
        - long_arg3 * long_arg4
    )
    return result

# Bad
def my_function(long_arg1, long_arg2, long_arg3, long_arg4): result = long_arg1 + long_arg2 - long_arg3 * long_arg4; return result

10.1.3: Imports:

When writing code, it is important to organize your imports in a clear and consistent manner. By placing your imports at the top of the file, you can make it easier for other developers to understand what external dependencies your code relies on. However, it's not enough to simply list your imports in a random order. To maximize readability, imports should be separated by a blank line, and organized in a specific order.

First, you should list any standard library imports that your code requires. These are built-in modules that come with the Python language, such as "os" or "sys".

Next, you should list any third-party imports that your code requires. These are external modules that you have installed using a package manager like "pip". Examples of third-party modules might include "numpy" or "pandas".

Finally, you should list any local application or library-specific imports that your code requires. These are modules that you have written yourself, or that are specific to your particular project.

By following this organization scheme, you can help ensure that your code is easy to read and understand, even for developers who are unfamiliar with your project. So don't forget to take a little extra time to organize your imports properly!

Example

# Good
import os
import sys

import requests

from my_module import my_function

# Bad
import os, sys
from my_module import my_function
import requests

10.1.4: Whitespace:

When writing code, it is important to use whitespace effectively. This means that while you should avoid using excessive whitespace, you should also use it to separate logical sections of your code. For example, you can use a single blank line to separate functions, methods, or class definitions. By using whitespace in this way, you can make your code more organized and easier to read.

In addition to separating code sections, it is also important to use whitespace around operators and after commas in lists, tuples, or dictionaries. This makes the code more readable and easier to understand, especially if someone else needs to review or modify it in the future.

Example

# Good
my_list = [1, 2, 3, 4]
result = x * y + z

# Bad
my_list=[1,2,3,4]
result=x*y+z

10.1.5: Naming Conventions:

  • Variables and function names should be lowercase, with words separated by underscores (e.g., my_variablemy_function).
  • Constants should be in uppercase, with words separated by underscores (e.g., MY_CONSTANT).
  • Class names should use the CapWords (PascalCase) convention (e.g., MyClass).
  • Method names should be lowercase, with words separated by underscores (e.g., my_method).

Example

# Good
class MyClass:
    my_variable = 10

    def my_method(self):
        pass

# Bad
class myclass:
    MyVariable = 10

    def MyMethod(self):
        pass

10.1.6: Comments:

When writing code, it is important to use comments to explain the purpose of the code, especially when it might be difficult to understand. Comments help other programmers who may need to work with your code to understand how it works and what it does.

It is recommended to use inline comments sparingly, as adding too many comments can make the code harder to read. When adding inline comments, it is important to separate them from the code with at least two spaces.

Always start comments with a capital letter and end with a period. This helps to maintain consistency and readability within your code, and can make it easier for others to understand what you are trying to accomplish.

In summary, comments are a vital part of writing good code, and can help to make your code more understandable and maintainable. So don't forget to add comments to your code!

Example

# Good
def my_function():
    # Calculate the result based on some logic.
    result = 42
    return result

# Bad
def my_function():
    result = 42  # Calculate the result based on some logic.
    return result

10.1.7: Docstrings:

Using docstrings, or triple-quoted strings, is a great way to provide documentation for your modules, classes, functions, and methods. This can help others understand the purpose and usage of your code more effectively, which can be especially important when working on projects with others or contributing to open-source projects.

Not only can good documentation make it easier for others to use and build on your code, but it can also make it easier for you to come back to your own code later on and remember how it works. In fact, many developers consider good documentation to be just as important as good code itself, since it can help ensure that your code is maintainable and usable in the long run. So, if you're not already using docstrings in your code, it might be worth taking the time to start incorporating them into your programming practices.

Example

# Good
def my_function(arg1, arg2):
    """
    Calculate the sum of two arguments.

    Args:
        arg1 (int): The first argument.
        arg2 (int): The second argument.

    Returns:
        int: The sum of the two arguments.
    """
    return arg1 + arg2

# Bad
def my_function(arg1, arg2):
    # Calculate the sum of two arguments
    return arg1 + arg2

These are just a few of the many guidelines provided by PEP 8. It is recommended to read the full PEP 8 document (https://www.python.org/dev/peps/pep-0008/) to familiarize yourself with all the guidelines and apply them consistently in your Python projects.

Exercise 10.1.1: PEP 8 Indentation

In this exercise, you'll practice fixing the indentation in a Python script to follow the PEP 8 guidelines.

Instructions:
Fix the indentation in the given Python script. The script should have 4 spaces for each indentation level.

Solution:

def my_function(arg1, arg2):
    result = arg1 + arg2
    return result

if __name__ == "__main__":
    num1 = 5
    num2 = 10
    sum_result = my_function(num1, num2)
    print(f"The sum of {num1} and {num2} is {sum_result}.")

Output:

The sum of 5 and 10 is 15.

Exercise 10.1.2: PEP 8 Imports

In this exercise, you'll practice organizing imports according to PEP 8 guidelines.

Instructions:
Reorganize the given imports in the Python script so that they follow the PEP 8 guidelines.

Solution:

import os
import sys

import requests

from my_module import my_function

print("Imports organized according to PEP 8.")

Output:

Imports organized according to PEP 8.

Note: The output will differ based on your system and the actual "my_module" you import.

Exercise 10.1.3: PEP 8 Naming Conventions

In this exercise, you'll practice applying PEP 8 naming conventions to a Python script.

Instructions:
Update the given Python script so that it follows the PEP 8 naming conventions for variables, functions, and classes.

Solution:

class MyClass:
    my_variable = 10

    def my_method(self):
        return self.my_variable * 2

def main():
    my_instance = MyClass()
    result = my_instance.my_method()
    print(f"The result is: {result}")

if __name__ == "__main__":
    main()

Output:

The result is: 20

10.1 PEP 8 - Style Guide for Python Code

As we approach the end of this book, it is important to note that the best practices for Python programmers are critical to the success of any project. While there are many best practices that programmers can follow, the ones presented here are essential to maintaining efficient, readable, and maintainable code. In this chapter, we will delve deeper into PEP 8, the official style guide for Python code, and explore how it can be used to improve your code. 

Furthermore, we will discuss other critical topics such as code organization, documentation, and testing. It is essential to understand these concepts in their entirety, as they will be crucial in ensuring that your Python projects are a success.

PEP 8 is the Python Enhancement Proposal that provides a set of guidelines and conventions for writing Python code. The primary purpose of PEP 8 is to make the code more readable and maintainable by providing a consistent style. Although PEP 8 is not a strict requirement, it is highly recommended to follow these guidelines to ensure that your code is easily understood by others, and even by yourself, in the future. 

Some of the key aspects of PEP 8 include:

10.1.1: Indentation:

When writing code, it is important to maintain consistent formatting. This can be achieved by using 4 spaces per indentation level, rather than mixing spaces and tabs. By doing so, the code becomes more readable and easier to understand for others who may need to work with the code in the future. Additionally, consistent formatting can help prevent errors and make debugging easier. Therefore, it is highly recommended to use 4 spaces per indentation level for all code you write.

Example:

# Good
def my_function(arg1, arg2):
    result = arg1 + arg2
    return result

# Bad
def my_function(arg1, arg2):
  result = arg1 + arg2
  return result 

10.1.2: Maximum Line Length: 

One way to improve code readability is to limit the number of characters per line. This can be achieved by setting a maximum line length of 79 characters. By doing this, the code becomes easier to read, especially when working with multiple files side by side. It allows for a more organized and structured codebase, as developers can quickly scan through the code and identify potential issues or areas for improvement.

Additionally, keeping the code within a certain length limit can also help with debugging and testing, as it minimizes the need for horizontal scrolling and makes it easier to spot errors.

Example:

# Good
def my_function(long_arg1, long_arg2,
                long_arg3, long_arg4):
    result = (
        long_arg1 + long_arg2
        - long_arg3 * long_arg4
    )
    return result

# Bad
def my_function(long_arg1, long_arg2, long_arg3, long_arg4): result = long_arg1 + long_arg2 - long_arg3 * long_arg4; return result

10.1.3: Imports:

When writing code, it is important to organize your imports in a clear and consistent manner. By placing your imports at the top of the file, you can make it easier for other developers to understand what external dependencies your code relies on. However, it's not enough to simply list your imports in a random order. To maximize readability, imports should be separated by a blank line, and organized in a specific order.

First, you should list any standard library imports that your code requires. These are built-in modules that come with the Python language, such as "os" or "sys".

Next, you should list any third-party imports that your code requires. These are external modules that you have installed using a package manager like "pip". Examples of third-party modules might include "numpy" or "pandas".

Finally, you should list any local application or library-specific imports that your code requires. These are modules that you have written yourself, or that are specific to your particular project.

By following this organization scheme, you can help ensure that your code is easy to read and understand, even for developers who are unfamiliar with your project. So don't forget to take a little extra time to organize your imports properly!

Example

# Good
import os
import sys

import requests

from my_module import my_function

# Bad
import os, sys
from my_module import my_function
import requests

10.1.4: Whitespace:

When writing code, it is important to use whitespace effectively. This means that while you should avoid using excessive whitespace, you should also use it to separate logical sections of your code. For example, you can use a single blank line to separate functions, methods, or class definitions. By using whitespace in this way, you can make your code more organized and easier to read.

In addition to separating code sections, it is also important to use whitespace around operators and after commas in lists, tuples, or dictionaries. This makes the code more readable and easier to understand, especially if someone else needs to review or modify it in the future.

Example

# Good
my_list = [1, 2, 3, 4]
result = x * y + z

# Bad
my_list=[1,2,3,4]
result=x*y+z

10.1.5: Naming Conventions:

  • Variables and function names should be lowercase, with words separated by underscores (e.g., my_variablemy_function).
  • Constants should be in uppercase, with words separated by underscores (e.g., MY_CONSTANT).
  • Class names should use the CapWords (PascalCase) convention (e.g., MyClass).
  • Method names should be lowercase, with words separated by underscores (e.g., my_method).

Example

# Good
class MyClass:
    my_variable = 10

    def my_method(self):
        pass

# Bad
class myclass:
    MyVariable = 10

    def MyMethod(self):
        pass

10.1.6: Comments:

When writing code, it is important to use comments to explain the purpose of the code, especially when it might be difficult to understand. Comments help other programmers who may need to work with your code to understand how it works and what it does.

It is recommended to use inline comments sparingly, as adding too many comments can make the code harder to read. When adding inline comments, it is important to separate them from the code with at least two spaces.

Always start comments with a capital letter and end with a period. This helps to maintain consistency and readability within your code, and can make it easier for others to understand what you are trying to accomplish.

In summary, comments are a vital part of writing good code, and can help to make your code more understandable and maintainable. So don't forget to add comments to your code!

Example

# Good
def my_function():
    # Calculate the result based on some logic.
    result = 42
    return result

# Bad
def my_function():
    result = 42  # Calculate the result based on some logic.
    return result

10.1.7: Docstrings:

Using docstrings, or triple-quoted strings, is a great way to provide documentation for your modules, classes, functions, and methods. This can help others understand the purpose and usage of your code more effectively, which can be especially important when working on projects with others or contributing to open-source projects.

Not only can good documentation make it easier for others to use and build on your code, but it can also make it easier for you to come back to your own code later on and remember how it works. In fact, many developers consider good documentation to be just as important as good code itself, since it can help ensure that your code is maintainable and usable in the long run. So, if you're not already using docstrings in your code, it might be worth taking the time to start incorporating them into your programming practices.

Example

# Good
def my_function(arg1, arg2):
    """
    Calculate the sum of two arguments.

    Args:
        arg1 (int): The first argument.
        arg2 (int): The second argument.

    Returns:
        int: The sum of the two arguments.
    """
    return arg1 + arg2

# Bad
def my_function(arg1, arg2):
    # Calculate the sum of two arguments
    return arg1 + arg2

These are just a few of the many guidelines provided by PEP 8. It is recommended to read the full PEP 8 document (https://www.python.org/dev/peps/pep-0008/) to familiarize yourself with all the guidelines and apply them consistently in your Python projects.

Exercise 10.1.1: PEP 8 Indentation

In this exercise, you'll practice fixing the indentation in a Python script to follow the PEP 8 guidelines.

Instructions:
Fix the indentation in the given Python script. The script should have 4 spaces for each indentation level.

Solution:

def my_function(arg1, arg2):
    result = arg1 + arg2
    return result

if __name__ == "__main__":
    num1 = 5
    num2 = 10
    sum_result = my_function(num1, num2)
    print(f"The sum of {num1} and {num2} is {sum_result}.")

Output:

The sum of 5 and 10 is 15.

Exercise 10.1.2: PEP 8 Imports

In this exercise, you'll practice organizing imports according to PEP 8 guidelines.

Instructions:
Reorganize the given imports in the Python script so that they follow the PEP 8 guidelines.

Solution:

import os
import sys

import requests

from my_module import my_function

print("Imports organized according to PEP 8.")

Output:

Imports organized according to PEP 8.

Note: The output will differ based on your system and the actual "my_module" you import.

Exercise 10.1.3: PEP 8 Naming Conventions

In this exercise, you'll practice applying PEP 8 naming conventions to a Python script.

Instructions:
Update the given Python script so that it follows the PEP 8 naming conventions for variables, functions, and classes.

Solution:

class MyClass:
    my_variable = 10

    def my_method(self):
        return self.my_variable * 2

def main():
    my_instance = MyClass()
    result = my_instance.my_method()
    print(f"The result is: {result}")

if __name__ == "__main__":
    main()

Output:

The result is: 20