Python basics for Grumpy Old Men (and other dummies)

Since I’ve recently spent a few weekends and evenings in an effort to learn Python, and gradually having started to fall in love with the language, I thought I should publish some aspects of the language that makes me appreciate it. Hopefully the few short examples below can provide inspiration to other ex-hackers from bygone times to take up programming again, as is the case for me.

What follows is in no way a complete description of the language – far from it, there are tons of materials available on the net for comprehensive description of the language – but instead a few tidbits that I hope and believe will enable anyone with previous experience of programming getting started with Python. Thus, the target audience here consists of folks who know what variables are, what built-in types to expect, what control structures to expect, what stuff like maps and iterators etc are, but have not been programming in Python before.

So, let’s get started. I’ll cover a bit of the basics, but the focus will be on more advanced stuff, things not easily available in more traditional languages such as C or C++.

First, the initially most confusing thing: Python is sensitive to indentation – blocks are defined not by any braces or parenthesis, but by intendation! – so you will have to indent your program correctly to get it thru the interpreter. Fortunately, any decent editor, such as emacs, will help you with that, but you will encounter strange bugs caused by erroneous indentation. Forewarned is forarmed…

In Python, you’ll find all the typical built-in types such as int, float, chr,bool etc, but also some more exotic types such as lists, tuples,sets and dictionaries, typically found in other types of languages, such as functional.

The latter built-in-types are specially convenient for text processing, but also very convenient to use in general programming, for instance, I made heavy use of all of them in my bit banging program manipulating AIS bitstreams, as documented in an earlier post on this blog.

A nice way to figure out the type of a varible is provided by the operator type(param), as below:

myInt = 1

print type(myInt) 

that will output <type ‘int’> on the screen

Obviously, Python also provides a string type, called str. Important to know about strings is that they are unmutable, i.e. you can not change an element of a string. Should you want to do so, you need to create a new string.

Python has a number of cool operators, such as isinstance, e.g:

fruit = ‘banana’

print isinstance(fruit, str)

Python provides a number of ways to iterate over different types of arrays, below a few of them:

for char in fruit:

        print char

another way to iterate over the elements – useful if you need to modify the elements – is to use the functions len() and range():

shoppingList = [‘beer’,’snacks’,’wine’,’Tylenol’]
print shoppingList

for i in range (len(shoppingList)):
     shoppingList[i] = ‘cheap’ + shoppingList[i]

print shoppingList

The above example also shows string concatenation.

You can slice arrays by colon notation:

print shoppingList[1:3]

Note that this will print the elements ‘cheepsnacks’ and ‘cheepwine’, i.e. second and third element of the list, not three elements, starting from the second, which at least I would have thought, coming from a C/C++ background. That is, the last index is the element after the one’s you want to slice.

A convenient reference to the last element is myList[-1], which will give you the last element of the list.

Lists can be manipulated by many built-in functions, for instance, you can append to a list:

shoppingList.append(‘sleeping Bag’)

print shoppingList

Lists are not constrained to contain elements of the same type, you can freely mix elements of different types in lists:

subList = [‘c’,4711,1.1]

print shoppingList

for element in shoppingList:
    print type(element)

A cool way to eliminate duplicates from a list is to do a conversion to a set type:

redundantList = [‘a’,’b’,’c’,’a’,’a’,’b’,’b’,’c’,’c’,’d’,’e’,’f’,’f’,’g’ ]
print list(set(redundantList))

Tuples are like lists, main difference being that they are unmutable. In my AIS decoding program, I used tuples to represent positions, that is latitudes & longitudes:

pos1 = (59.33,18.02)
pos2 = (33.05,16.03)

pos1,pos2 = pos2,pos1 # swap the positions – note the cool tuple assigment! 

print “swapped position:”,pos1, pos2

If you’d try to change the contents of the tuple, you’ll get an error:

pos1[0] = 0.0

Traceback (most recent call last):
File “”, line 44, in <module>
pos1[0] = 0.0
TypeError: ‘tuple’ object does not support item assignment

An example of higher order functions:

# filter, map, reduce

def f(x):return x % 2 != 0 # odd numbers only
print filter (f,range(10)) # 0-9

def areacircle(r):return r*r*3.14
print map (areacircle,range(10))

def add(x,y):return x+y
print reduce(add,(range(10)))

fib = [0,1,1,2,3,5,8,13,21,34,55,89]

print fib
print filter (f,fib)

def square(x) : return x * x

print map(square,fib)

print reduce(add,fib)
print reduce(add,map(square,fib))
print reduce(add,filter(f,map(square,fib))) #sum of all odd squares

Dictonaries are very useful for all sorts of things, anytime you need a mapping between different elements:

[for any politically correct or otherwise sensitive souls out there: since I’m not a native English speaker, I have no problems whatsoever naming a dictionary variable to ‘mydic’… :-)]


mydic = {‘ett’:’one’,’tva’:’two’,’tre’:’three’}
print mydic
print len(mydic)
print ‘one’ in mydic
print ‘ett’ in mydic
vals = mydic.values()
print vals
print ‘one’ in vals
print type(mydic)
print isinstance(mydic,dict)

Dictornaries have many cool functions, like here, where I create a letter frequency table in just a couple of lines of code:

#letter frequency counter using dict data type
letterlist = [‘a’,’b’,’c’,’a’,’b’]
freq = dict()

for k in letterlist:
freq[k] = freq.get(k,0) + 1 # if letter not there, create it, init counter to 0, otherwise inc counter

To iterate over the keys and values in a dictionary, we can use the iteritems() iterator:

for k,v in freq.iteritems():
     print k,v

So far, everything I’ve covered is part of the Python language itself. In addition to all the cool capabilities of the language, there’s a lot of external modules available. Below, I’ll show a tiny bit of a huge and very well documented module called bitstring, very convenient to use as soon as you are about to do serious bit banging:

import bitstring
a = bitstring.BitArray(uint=8,length=8)
b = bitstring.BitArray(uint=5,length=8)

def hamming_distance(a, b):
return (a^b).count(True)

print a.bin
print b.bin
print “hamming distance:”,hamming_distance(a,b)

I hope that these few short examples have wetted your appetite for Python. There’s vast lot of more to be learned for sure, but with these basic constructs I’ve been able, in a very short time, to create powerful programs in different areas, such as collection and manipulation of massive amounts of text for social network analysis, and really low level bit banging for encoding and decoding bitstreams.

About swdevperestroika

High tech industry veteran, avid hacker reluctantly transformed to mgmt consultant.
This entry was posted in development. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s