Python Coding Techniques and Programming Practices

Introduction:

Python Coding techniques and programming practices are  one of the features of a professional programmer. While writing  code to solve a problem programmer should make simple choices and  have to use basic techniques. This completely depends on the programmer's skill and expertise and how wisely he make choices.

Coding techniques are basically focused on improvising the readability and maintainability of the code. 

  • Readability of source code has a direct impact on the developer so, while coding one should try to write code that can make easy others read and understand.
  • Code  maintainability  focuses on making enhancements to existed software system such as adding new features, modifying existed features, fixing bugs and performance improvement easily.

Programming practices are  mainly focused on the performance of the code and its enhancements.

Coding Techniques:

 coding techniques serve developers as a guide for developing a standard code for a software system. These are categorised into three sections.

  1. Names
  2. Comments
  3. Format

Names:  

  Names are most influenceable part  to understand the logical flow or concept of the code what it mean to be or what it  do . ( use related words as variables )

  •  Camel case Notation :  variable name is formed with more than a single word  next words begin with a uppercase letter so that we can identify words.
    • Class level varibale names should starts with uppercase letters
    • attribute, method names should starts with lowercase  letters
    • Examples:   isActive, UserRegistration(class), UserLogin, totalPrice, userDetails(attribute), calculateDiscount(method) 
  • Delemeter Notation :  variable name is formed with multile words , these words use a delemeter to join and form variable.
    • in genereal  "_" is used as delimeter.
    •  is_active, User_Registration(class), User_Login, total_price, user_details(attribute), calculate_discount(method)
  • Tips: 
    • variable names should be as small as possible and meaningful
    • don't use nagative logic for varibales names (ex: is_not_logged_in )
    • think 3-4 minutes about variable names.

Comments:

  • comments are used in coding for writing help text
  • comments provide a short description of the code
  • use comments when they are needed don't write comments on unnecessary things

Format :

It is very important when we are coding for larger projects because the code is altered by a team. so, programmer should format the code in such way that others can easily debug the code and can modify it easily. 

  • Don't write clumsy code use line breaks wherever required or use variables. It makes the code more readable.
  • Use proper indentation

  follow  pep8 standards  

Python code optimizations:

1. Looping over numbers:

result = []
for i in range(100):
     if  i% 5 == 0:
         result.append(i)

Final output: 
result = 
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
 

Better way

result = range(0,100,5)
# range(start, end, step)

 

2.  Looping over a list

colours = ['red', 'green', 'blue', 'yellow']
for i in range(len(colours)):
     print colours[i]

Better way

for colour in colours:
     print colour

3. Looping over a list and its idices

for i in range(len(colours)):
     print i, '-->', colours[i]

Better way

for i, colour in enumerate(colours):
     print i, '-->', colour

4. Looping backwards

for i in range(len(colours), -1, -1, -1):
     print colours[i]

Better way

for colour in reversed(colours):
      print colour

 

5. sorting  in ascending order

for colour in sorted(colours):
     print colour

6. sorting in descending order

for colour in sorted(colours, reversed=True): 
     print colour

7. looping over two collections 

names = ['Anji', 'Ben', 'Catherin']
colours = ['red', 'green', 'blue', 'yellow']
n = min(len(colours), len(names))
for i in range(n):
     print names[i], '-->', colours[i]

Better way

for name, colour in zip(names, colours):
      print name, '-->', colour

8. looping over dictionary keys and values

for key in dict:
    print key, '-->', d[key]

Better way

for key, value in dict.items():
     print key, value

Best way

for key, value  in dict.iteritems():
     print key, '-->', value 

10. construct a dictionary from two lists

names = ['Steve Jobs','Bill Gates ','Jeff Bezos']
org = ['Apple', 'Microsoft', 'Amazon']
d = dict(zip(names, org))

Better way

from itertools import izip
d = dict(izip(names, org))

izip is faster than zip,   zip computes all the list at once, izip computes the elements only when requested. One important difference is that 'zip' returns an actual list, 'izip' returns an 'izip object', which is not a list and does not support list-specific features (such as indexing).

11. using comparison operator 

is_master = None
if role == 'master':
    is_master = True
else:
    is_master =  False

Best way 

is_master = role == 'master'

note: comparison operator always returns a boolean[True, False]

12. achieve  switch/case in python with dict

def switch(case):
      cases = {1: 'case 1',
                    2: 'case 2',
                    3: 'case 3'}
         return cases.get(case, "default")
    

13. convert  a list of strings to numbers

str_numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
numbers = []
for i in str_numbers:
      numbers.append(int(i))

Best way 

numbers = map(int, str_numbers)

14. multiplying numbers  a list of numbers

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = 1
for num in numbers:
     result  *= num

Best way is 

def multiply(a, b):
      return a*b
result = reduce(multiply, numbers)

15. finding multiples of 3  from a random set of numbers

numbers = [2, 7, 5, 4, 6, 1, 8, 9, 7, 3, 7, 5, 9, 3, 8, 4, 9, 6, 8, 5, 9, 7, 2, 6, 8, 8, 7, 6, 5, 9, 1, 1, 5, 5, 7, 4, 1, 0, 1, 1, 5, 4, 8, 4, 8, 7, 7, 8, 0, 1, 6, 8, 4]
list = []
for num in numbers:
      if num % 3 == 0:
            list.append( num )
 

Better way is 

def devide3(n):
      return n%3 == 0
list = filter(devide3, numbers)

Posted On 12 June 2014 By MicroPyramid


Need any Help in your Project?Let's Talk

Latest Comments
Unit testing with selenium-python

Unit testing with selenium-python. Unit test case example to test the front-end

Continue Reading...
Tips to choose the best custom software development company

Choosing the best company for your software development needs is the most important step. This blog explains you tips to outsource custom software development services.

Continue Reading...
WSGI explanation with simple APP

The main goal of WSGI is to facilitate easy interconnection of servers and web frameworks/applications. WSGI defines a standerd API for web servers(uWSGI, Twisted, Gunicorn) …

Continue Reading...
Understanding self and __init__ method in python Class.

Understand self and __init__ method in python Class?
Before understanding the "self" and "__init__" methods in python class, it's very helpful if we have the idea …

Continue Reading...
List of python class special methods or magic methods

python class special methods or magic methods. magic methods allow us to override or add the default functionality of python objects. One of the biggest …

Continue Reading...
Building and Parsing XML Document using Python

Creating XML document with required elements, Then Parsing it using Python to generate a serialized form of its contents.

Continue Reading...
Working with python collections Counter

Python collections - Counter is to count the frequency of character, OrderedDict is to track the order of the contents in which they are added …

Continue Reading...
Python to Debian package: Simple, Easy and Fast

Packaging python script to debian follows strict instructions, using the following instructions, most of the steps can be skipped hence making it easy and fast.
If …

Continue Reading...
Sending SMS, MMS using Twilio.

A simple Tutorial on sending SMS and MMS in python using Twilio. In this tutorial you will learn how to send SMS, MMS and checking …

Continue Reading...
Customize and Embed Vimeo Videos using Python Requests.

Using python requests and vimeo endpoints it becomes very easy and simple to upload our videos and customize them.

Vimeo Access token:
1. Create an …

Continue Reading...
Getting Started with the IPython Notebook

IPython is a set of tools developed to make it easier for the programmers to work with Python and data. IPython provides extensions to the …

Continue Reading...
Python Arrow To Show Human Friendly Time

Arrow is a python library and command-line tool to genrerate, manipulate dates, times, timestamps.
use of arrow:
With the use of arrow, we can also create, manipulate, …

Continue Reading...
Working with python collections part 1

Python Collections - named tuple is to access by the names specified and deque is to append and pop the elements from both sides of …

Continue Reading...
Building Documentation with readthedocs

In this blog, I'm going to explain you how to write the Sphinx docs using reStructuredText to host in the Read the Docs.

Installing Sphinx

Continue Reading...
Create excel file, Insert image, Draw Bar Graphs in excel files in python using xlsxwriter

Xlsxwriter is a python module through which we can write data to Excel 2007+ XLSX file format. In this blog post we learn to write …

Continue Reading...
Integrate Twitter Social API into Django App

Integrating Twitter sign in (OAuth) in Django App, which includes
1. Capturing username via Twitter Login
2. Updating authenticated user current status on twitter(tweets).

Continue Reading...
How to implement Case Insensitive CSV DictReader in python

In general use cases we upload the CSV files to the system to store huge amount of data by uploading single file. For example in …

Continue Reading...
Python using yield and generators.

Generators are memory efficient. They allow us to code with minimum intermediate arguments, less data structures. Generators are of two types, generator expressions and generator …

Continue Reading...
Introduction to Object Oriented Programming with Python 3

Introduction to Object Oriented Programming with Python

Continue Reading...
Python Coding Techniques and Programming Practices

Coding techniques and programming practices are one of the features of a professional programmer. While writing code to solve a problem programmer should make simple …

Continue Reading...
FABRIC – LEARNING PART 2

Using Fabric, we can develop interactive script for ec2 region, ec2 flavour amazon web services. For this, you need aws account, security group, key pair, …

Continue Reading...
Generating PDF Files in Python using xhtml2pdf

There are many ways for generating PDF in python. In this post I will be presenting PDF files generation with xhtml2pdf.

xhtml2pdf: xhtml2pdf is a …

Continue Reading...
Using Python xlwt generating CSV writer and Excel files

In most of the cases, you need to export the data from your database to different formats. In this post I will show you how …

Continue Reading...
How to access development server publicly using Localtunnel

We do need to expose our local server to hit call-back URLs while programming with other APIs. There is a tool called local tunnel from …

Continue Reading...
How to generate PDF Files from HTML In Python using PDFKIT

There are many approches for generating PDF in python. pdfkit is one of the better approache as, it renders HTML into PDF with various image …

Continue Reading...
Converting Audio and Video files using FFMPEG Tool

FFMPEG is a command-line tool that converts audio or video to required formats, which handle multimedia data. It can also capture and encode in real-time.

Continue Reading...
Python Web Scraping with Beautiful soup

Download all One Piece animation series episodes by scraping site using BeautifulSoup python library.

Continue Reading...
Publishing Python Modules with PIP via PyPi

We'll install so many packages in our day to day python development. Now in this blog post, we'll try to know how to create our …

Continue Reading...
Programming with python: Decorators

Python decorators supports aspect-oriented programming. It is used to add or modify code in functions or classes. Using decorators will provide security, tracing, looking ..etc …

Continue Reading...
Vim for Python Web Development

Having a good environment setup is important for effective, fast and easy coding. We have different IDE's like eclipse, pycharm, sublime etc.. which are powerful …

Continue Reading...
Understanding Python Properties

Python Properties is a class for managing class attributes in Python. Property( ) is a built-in function that creates and returns a property object

Syntax:
attribute_name …

Continue Reading...
QRCode generation in python

A Quick Response code(QRCode) is a two-dimensional pictographic code used for its fast readability and comparatively large storage capacity. The code consists of black modules …

Continue Reading...
Understanding Audio Quality: Bit Rate, Sample Rate

Audio Quality is the accuracy and enjoyability of the audio which the user can listen from an electronic device. Audio quality depends upon the bit …

Continue Reading...
Programming with python Descriptors (_get_, _set_, _delete_) - MicroPyramid

Python descriptors are object attributes that are only invoked for new style of classes. Python descriptors comes under the category of meta programming(code that manipulates …

Continue Reading...
Debugging in Python

When something goes wrong with your code instead of using standard debugging techniques such as print statements use debugging tools. I found two great tools …

Continue Reading...
Python development environment on windows

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of …

Continue Reading...

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties