Structuring Python Programs


In this tutorial, we are going to see some best practices for structuring the Python programs. Let's see one by one

Use a tab for indentation

Using a tab for indentation in the code make code more readable instead of using random spaces for multiple functions and methods. You can set the number of spaces for a tab in any code editors' settings.

Example

# example
def sample(random):
# statement 1
# statement 2
# ...
return random

Don't write more than 79 characters in a line

Writing more than 79 characters in a line is not recommended Python. Avoid this by breaking line into multiple lines using the escape character (). See the example below.

Example

# example
def evaluate(a, b, c, d):
   return (2 ** (a + b) / (c // d) ** d + a - d * b) \
   - (3 ** (a + b) / (c // d) ** d + a - d * b)

If you have to check multiple conditions in if statement, then it will be more than 79 characters. Use any one of the following methods.

Example

if (
   a + b > c + d and
   c + d > e + f and
   f + g > a + b
):
print('Hello')
if a + b > c + d and \
   c + d > e + f and \
   f + g > a + b:
   print('Hello')

Using docstrings

Use docstring in the functions and classes. We can use the triple quotes for the docstrings. some examples below.

Example

def sample():
   """This is a function"""
   """
   This
   is
   a function
   """
class Smaple:
   """This is a class"""
   """
   This
   is
   a class
   """

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Updated on: 11-Jul-2020

234 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements