Python

Python is a general interpreted high level language, with code readability, clarity and expressiveness at it's core. You can find a lot of information about the language by browsing their website at http://www.python.org. Or alternatively stick around and browse some of the topics I've written about python below.

Recent Python Articles

To add a directory to the python path in Linux you can add the path to the startup script in .profile or .bashrc (dependig on which shell you are using) .These files will be found in your home directory. So open up a terminal (Ctrl+Alt+T) and type pwd to make sure you are in your home directory. Then type:

cp .profile .profile_old

This will make a copy of the file you are about to modify so if you mess it up you can revert to the old one.(always a good thing to do before modifying a config file). Now add the following to the end of the file and save and exit.

export PYTHONPATH=$PYTHONPATH:/home/user/directory

Where /home/user/directory is the path of the directory you want to add. This file (.profile or bashrc) depending on the shell you use is run every time you log on to the system so the path will be added the next time you log on. So log out of the system and log back in and you can check to see if the path has been added by using the following commands in the idel interpreter:

import sys, pprint

pprint.pprint(sys.path)

 

 

Post date: Thursday, June 20, 2013 - 16:41
Tags:

>>> import sys, pprint

>>> pprint.pprint(sys.path)

This returns a list of places where python will look for modules, so you can save a module in any of these places(although you should create your own folder and add this to your path for any modules you create)  and import a module  using import

['',

 'C:\\Python27\\Lib\\idlelib',

 'C:\\my_python_modules',

 'C:\\WINDOWS\\system32\\python27.zip',

 'C:\\Python27\\DLLs',

 'C:\\Python27\\lib',

 'C:\\Python27\\lib\\plat-win',

 'C:\\Python27\\lib\\lib-tk',

 'C:\\Python27',

 'C:\\Python27\\lib\\site-packages',

 'C:\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode']

 

Post date: Thursday, March 21, 2013 - 12:40
Tags:

If you don’t want to change the environment variables on your machine you can run your scripts from the command prompt by specifying the full path to the python.exe like this;
C:\>C:\Python27\python hello.py
If you want to change it then Start and right-click  My Computer and click on Properties then click Advanced and click Environment Variables. Now scroll down along system variables  until you see a variable called PATH. Click this and click edit. Now go to the end of the string and add ;C:\Python27\(Or whatever your path to you python installation is). Now click OK and OK and OK again and now you’re done. The path depends on your python version installed. To find out what your path should be you could open up IDEL interpreter and type
>>> import sys, pprint
>>> pprint.pprint(sys.path)

Post date: Thursday, March 21, 2013 - 12:38
Tags:

Type help() for interactive help, or help(object) for help about object.
>>> help()
Welcome to Python 2.7!  This is the online help utility.
 
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/tutorial/.
 
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".
 
To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics".  Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".
 
To find out information on built-in function, type the function name after the  help> prompt. Here we will find out about the function open().
help> open
Help on built-in function open in module __builtin__:
 
open(...)
    open(name[, mode[, buffering]]) -> file object
   
    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.  See file.__doc__ for further information.

Post date: Thursday, March 21, 2013 - 12:26
Tags:

There are a number of applications that let you create a windows executable from your python programs/scripts. The one I found most user friendly was PyInstaller which you can download from their website here.

Once downloaded unpack/unzip all files to a path of you choice. For the purpose of this document I put mine in the path C:\Python27\pyinstaller.

For Windows (32/64bit), Linux (32/64bit) and Mac OS X (32/64bit) precompiled boot-loaders are available. So the installation is complete now.

To be able to run this from the command prompt you will need to have added the location of the python executable to you system path. To see how to do this go here

 

To build your project, from the command prompt change your directory to the folder where you unpacked PyInstaller files. Mine was   C:\Python27\pyinstaller and run this:

python pyinstaller.py [opts] yourprogram.py

 

yourprogram.py refers to the name of your python script which you want to package.

The [opts] part refers to the different options you can use, if left blank PyInstaller will use the defaults and you will end up with a sub-directory named after your program name in the path  your/path/to/pyinstaller/ directory. The generated files will be placed within the sub-directory yourprogram/dist; that's where the files you need will be placed. A specification file called yourprogram.spec will be created in the sub-directory yourprogram, too.

For example to package all your distribution files in the one executable which can be run on any windows machine without any dependencies use the option –onefile

pyinstaller.jpg

 

For a list of all the options available go to the PyInstaller website here.

Post date: Wednesday, September 5, 2012 - 15:35
Tags:

An exception is what python uses to flag a exceptional behavior in a program. These are objects that if not dealt with by the program will terminate the program with an error or traceback.

>>> 1/0
Traceback (most recent call last):
File "", line 1, in
1/0
ZeroDivisionError: integer division or modulo by zero
>>>

As you can see a ZeroDivisionError has been raised. To see a list of all the exception available to you use:

>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__', '__package__']
>>>

Exception handling allows the programmer to catch the error and do something about it, rather than letting the program fail. We will use the divide by 0 error above to show you how to catch an exception.

# catch_exception.py
num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
try:
result = num1/num2
print result
except ZeroDivisionError:
print "You can't divide by zero"

Post date: Friday, August 24, 2012 - 12:03
Tags:

To make a new style class simply subclass the built in class object

class NewStyleClass(object):
some methods here

To initialize the class automatically we use the constructor by creating a method using __init__

class MyClass(object):
def __init__(self):
myVar = 78

>>> c = MyClass()
>>> c.myVar
78
>>>

Each method will have the first argument referring to itself usually called self. In the example above we created an instance of MyClass called c . Now we can say that the constructor and any other methods for our object c will have their first argument set to c in-place of the self, so we can access the myVar variable using c.myVar

Post date: Thursday, August 23, 2012 - 17:04
Tags:

Polymorphism comes from two Greek words meaning ‘many shapes’ and is best explained by a real world example. The feet of a human are a very different shape to that of a centipede, but they have basically the same function, walking. So we can refer to the feet of a human, centipede, horse, or frog without confusion. Polymorphism allows the programmer to give the same names to methods and attributes that play similar roles in distinctive classes.
As an example we will use a built-in operator, function or method on an object without knowing what kind of object it is.

Here we use the count method on a string.

a = 'This is a string'
print a.count('s')
>>>
3

Now we will use the count method on a list.

b = [1,2,3,4,5,'s','i','n']
print b.count('s')
>>>
1

Post date: Thursday, August 23, 2012 - 16:44
Tags:

This is a small function with no name that contains an expression and returns its result. We will use it in the built in function filter: filter(function, iterable).

>>> numbers = [1,2,3,4,5,6,7,8,9,10]
>>> filter(lambda n: n % 2 == 0, numbers)
[2, 4, 6, 8, 10]
>>>

Post date: Thursday, August 23, 2012 - 16:13
Tags:

This is where a function calls itself. Let’s look at a classic example of recursion, the power of something. First we define the problem:

    power(x, 0) is 1 for all numbers x.
    power(x, n) for n > 0 is the product of x and power(x, n-1).


def power(x, n):
if n == 0:
return 1
else:
return x * power(x, n-1)

Post date: Thursday, August 23, 2012 - 16:12
Tags:

You can allow a function to take many parameters by adding the * before the argument>

def printMany(*param): print param
Works like this

printMany('this','is','a','string')
('this', 'is', 'a', 'string')

Post date: Thursday, August 23, 2012 - 15:40
Tags:

Takes two lists as parameters and returns a list of tuples where the i-th tuple contains the i-th items from each sequence. This is best explained with an example.

>>> x = ['a','b','c']
>>> y = ['d','e','f']
>>> zipped = zip(x,y)
>>> zipped
[('a', 'd'), ('b', 'e'), ('c', 'f')]
>>>

Post date: Thursday, August 23, 2012 - 15:31
Tags:

Abstraction lets the programmer group a bunch of statements together into functions.

text = 'This is a string'
result = 0
text = text.replace(' ','')#get rid of spaces
for char in text:# now count the characters
result += 1
>>>result
13

Now instead of typing all this code out again the next time we need to count the number of characters in a string we could put it in a function like this.

#countChars.py

def countchars(string):
'''This is a program that counts the number of characters in a sentence
and returns the result'''
result = 0
string = string.replace(' ','')
for char in string:
result += 1
return result

Now when we need to count the number of chars in a string we do this.

text = “Your mother was a hamster and your father smelt of elderberry”
print countChars(text)
51

By putting your comments directly after the def statement you automatically create a doc string which can be accessed like this.

>>> countChars.__doc__
'This is a program counts the number of characters in a sentence and returns the result'
>>>

Post date: Thursday, August 23, 2012 - 14:11
Tags:

Concatenate two lists

>>> list1 = [1,2,3,4,5,6,7,8]
>>> list2 = [9,10,11]
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 10, 11]
>>> list2
[9, 10, 11]
>>>

Post date: Thursday, August 23, 2012 - 14:01
Tags:

Filter takes a list and applies a function to that list.
filter(function, iterable) Construct a list from those elements of iterable for which function returns true.

>>> list
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>> filter(lambda n: n%3 == 0, list)
[0, 6, 12, 18]
>>>

Post date: Thursday, August 23, 2012 - 13:58
Tags:

Map

Maps one sequence into another. map(function, iterable, ...) Apply function to every item of iterable and return a list of the results.

>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> map(lambda n: n *2, lst)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
>>>

Post date: Thursday, August 23, 2012 - 13:24
Tags:

A way of making lists from lists

>>> [x for x in range(20) if x%2 == 0]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>

Post date: Thursday, August 23, 2012 - 13:22
Tags:

Sequences are numbered from 0 upward so you can access them like this

>>> myString = "This is a string"
>>> string[0]
'T'
>>> string[0:4]
'This'
>>>

Post date: Thursday, August 23, 2012 - 13:21
Tags:

To add a module to your program, add this to the top of your program

import sys
sys.path.append('c:/my_python_modules')

Post date: Thursday, August 23, 2012 - 13:17
Tags:

To find out what the built in module math contains first import it using
import math
Then perform a dir() on it
dir(math)
This returns a list of all the functions available in that module
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

To filter out all the functions in the list that begin with an _ as we are not supposed to use these outside the module, we could use:
[funct for funct in dir(math)if funct[0] != '_']
['acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

Post date: Thursday, August 23, 2012 - 13:14
Tags:

To find your python path type the following in the interpreter

import sys, pprint
pprint.pprint(sys.path)

This returns a list of places where python will look for modules, so you can save a module in any of these places(although you should create your own folder and add this to your path for any modules you create) and import a module using import.
['',
'C:\\Python27\\Lib\\idlelib',
'C:\\my_python_modules',
'C:\\WINDOWS\\system32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode']

As you can see I've added C:\\my_python_modules to my windows path.

Post date: Thursday, August 23, 2012 - 12:20
Tags:

If you don’t want to change the environment variables on your machine you can run your scripts from the command prompt by specifying the full path to the python.exe like this;
C:\>C:\Python24\python hello.py
If you want to change it then Start and right-click My Computer and click on Properties then click Advanced and click Environment Variables. Now scroll down along system variables until you see a variable called PATH. Click this and click edit. Now go to the end of the string and add ;C:\Python27\ or the path to your version of python. Now click OK and OK and OK again and now you’re done. The path depends on your python version installed. To find out what your path should be you could open up IDEL interpreter and type

import sys, pprint
pprint.pprint(sys.path)

Post date: Thursday, August 23, 2012 - 12:02
Tags:

Help
Type help() for interactive help, or help(object) for help about object.
>>> help()
Welcome to Python 2.7! This is the online help utility.

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module also comes with a one-line summary
of what it does; to list the modules whose summaries contain a given word
such as "spam", type "modules spam".

To find out information on a built-in function such as open type open after the help> prompt
help> open
Help on built-in function open in module __builtin__:
open(...)

open(name[, mode[, buffering]]) -> file object

Open a file using the file() type, returns a file object. This is the
preferred way to open a file. See file.__doc__ for further information.

Post date: Thursday, August 23, 2012 - 11:57
Tags: