Here are a few Python coding tips for every beginner coding geek

Python coding tips

Everyday is a new opportunity to progress with your coding skills. There are many good resources available on the world wide web teaching best practices on some of the most used programming languages in the software development industry such as Php, Java, C++, Ruby and Python.

The zen of python

Open the Python interactive shell and run the following command:

import this

Read the output coming from the above command carefully as it is truly important for the Python coder:

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

 

Clear your python shell with this command

Most of the time when working on the interactive python shell one feels the need to run a clearing operation so the mind does not get overwhelmed by unwanted information. The clear utility is used on unix based systems to ‘refresh’ the console.

It is possible to execute system commands through the os module which is available by default in the Python library.

The following piece of code can help to clear the Python console on operating systems such as Linux and Mac OS X.

import os
os.system('clear')

Windows based systems have the cls command for clearing the screen. Back in the day, I used to make use of the command prompt on Windows 7, so every time it was necessary to clear the console I made use of the following command:

cls

Logically it makes sense to just replace the name of the command in the os.system call after importing the module for the above code to work on Windows systems.

os.system('cls')

Be careful when creating tuples

Many beginner coders think that running the following piece of code in the Python console is going to return a tuple built in object, but once the code is executed what you think to be true is actually false.

(1)

The Python shell returns an integer after running the above piece of code.

1

Based on this practical example, one can easily tell that the parentheses are not the constructor of a tuple object, they just make the code more readable.

Try to run the following code in the Python interactive shell and see for yourself what kind of object is returned.

(1,)

The following is the result being returned while executing the above piece of Python code.

(1,)

It is highly recommended to always include the comma when constructing tuple objects with only one element.

For example, in the case shown below the comma after the last element available in the tuple is not needed.

(1, 2)

Executing the above code, the following gets displayed on the interactive Python shell:

(1, 2)

The idiomatic way of testing if a variable is set to ‘None’

You may be tempted to use the following code:

a = None
if not a:
    print(a)

Don’t! The above is not the idiomatic way to check if a variable in Python programming language has a value of None. To test if a variable is None in an idiomatic way use this syntax:

if a is not None:
    print(a)

Get the documentation of a Python object

Getting help on a specific function or module from the interactive shell becomes really easy using the help() command.

help('os')

Running the above command the Python shell gets information on the built in module os and prints it out for the user to read.

The output should look similar to the following:

Help on module os:

NAME
    os - OS routines for NT or Posix depending on what system we're on.

FILE
/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib
/python2.7/os.py

MODULE DOCS
    http://docs.python.org/library/os

DESCRIPTION
   This exports:
   all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.
    os.path is one of the modules posixpath, or ntpath
    os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'
    os.curdir is a string representing the current directory ('.' or ':')
    os.pardir is a string representing the parent directory ('..' or '::')
    os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
    os.extsep is the extension separator ('.' or '/')
    os.altsep is the alternate pathname separator (None or '/')
    os.pathsep is the component separator used in $PATH etc

The help command is very handy to the Python coder especially if there is not an internet connection available for doing research and consulting the official documentation.

It is also possible to research a specific function of the module os, as shown here:

help('os.getenv')

The os.getenv function is used to get the value of an environment variable. If not present, ‘None’ is returned.

Try to run the above command on the Python interactive shell and check if the following information gets printed out:

Help on function getenv in os:

os.getenv = getenv(key, default=None)
    Get an environment variable, return None if it doesn't exist.
    The optional second argument can specify an alternate default.
(END)

Format strings

The are many ways of formatting strings in Python. The following works with a template and interpolation values.

name = 'Bob'
cows = 10
sentence = '%s has %i cows' % (name, cows)

The values are being stored in a tuple. Each one of the values must match a specific formatting string in the template.

Print the sentence with the help of the print statement:

print(sentence)

The following piece of text will be printed on the console:

Bob has 10 cows

The %s stands for string values. What about the %i operator? According to the official documentation this operator converts an integer to a string for the purpose of string formatting.

The above case is a very clear example of how string formatting in Python is done.

Swap values

Swapping values in Python is easier than in any other programming language I have tried so far.

a = 3
b = 5
a, b = b, a

To verify the values are being swapped, do the following checks.

print(a)
print(b)

Comments and docstrings

Commenting the codebase is truly important for the future of a Python project as it helps to understand how stuff works under the hood, and is especially handy if you are dealing with multiple projects at the same time.

A comment in Python starts with the # syntax.

# This is a comment in Python programming language

What about docstrings? Python developers use docstrings to help the user learn how to use a specific part of the code, for example a function inside a module or  a method in some instance.

A docstring is defined with the help of triple quotes.

"""
This is a docstring.
"""

The following is a real world piece of code where the docstring is being used.

def _add_video(self, url, filename, **kwargs):
 

   """Adds new video object to videos.

    
     :param str url:
 The signed url to the video.
    
     :param str filename:
 The filename for the video.
    
     :param kwargs:
 Additional properties to set for the video object.

   """
    
    # create the Video instances
    
    video = Video(url, filename, **kwargs)
     
    self._videos.append(video)
    
    self._videos.sort()
    
    return True

 

Conclusion

As it is with learning any new skill, practice is the key to improvement. Mistakes too! You can never go the right way if you have not experienced what it feels like to go the wrong way.

The above Python tips can be really useful to the beginner coder to help them improve their skills and become intermediates in no time!