Learning Python – Part 5

Forewords

A while back I decid­ed to try and learn Python for the hell of it as it seems like an inter­est­ing lan­guage and has some of the most con­cise and user-friend­ly syn­tax. Hav­ing spent some time going through a num­ber of dif­fer­ent learn­ing sources and mate­ri­als (like the offi­cial site python.org which has a very help­ful tuto­r­i­al sec­tion) I have put togeth­er a set of notes I made as I was learn­ing and hope­ful­ly they can be use­ful to you as a quick list of how-to code snip­pets.

All the code snap­shots I’m show­ing here are tak­en from the IDLE Python shell.

Input and Output

The repr() func­tion gen­er­ates rep­re­sen­ta­tions that can be read by the inter­preter, str() func­tion gen­er­ates a human-read­able of the val­ue:

clip_image001

 

If an object doesn’t have a par­tic­u­lar rep­re­sen­ta­tion for human con­sump­tion, str() will return the same val­ue as repr(), e.g. lists and dic­tio­nar­ies:

clip_image002

 

You can use the string.rjust(), string.ljust() or string.center() func­tion to left-jus­ti­fy, right-jus­ti­fy or cen­ter a string of giv­en width by padding it with spaces:

clip_image003

 

You can use the string.zfill() func­tion to pad a numer­ic string on the left with zeros:

clip_image004

 

You can use string.format() method to for­mat the string out­put of your code:

clip_image005

 

You can also use named argu­ments:

clip_image006

 

An option­al ‘:’ and for­mat spec­i­fi­er can fol­low the field name to allow greater con­trol over how the val­ue is for­mat­ted:

clip_image007

 

Pass­ing an inte­ger after the ‘:’ will cause that field to be a min­i­mum num­ber of char­ac­ters wide:

clip_image008

 

For a very long string, you could even ref­er­ence vari­ables to be for­mat­ted by name using a dic­tio­nary:

clip_image009

Or you could unpack the dic­tio­nary first:

clip_image010

 

You can use the open() func­tion to get a file object, to open a file for writ­ing:

clip_image011

The first para­me­ter being the file name, the sec­ond the mode which can be one of the fol­low­ing:

clip_image012

 

To open a file and read its con­tents:


clip_image013

 

To read one line at a time

clip_image014

 

To read the lines in the file as an array of strings:

clip_image015

 

You can also read x num­ber of bytes at a time:

clip_image016

 

But remem­ber, you always read start­ing from the posi­tion where your last read fin­ished:

clip_image017

 

To write to a file:

clip_image018

 

You can only write string con­tents to a file, which means you’d need to con­vert oth­er objects to string first:

clip_image019

 

To flush the file buffer and actu­al­ly write them to the file, use the close() func­tion, after which you’ll need to open the file again:

clip_image020

 

You can use the tell() func­tion to find out your cur­rent posi­tion in the file:

clip_image021

 

You can use the seek() func­tion to change the file object’s cur­rent posi­tion, seek(offset, from_what):

clip_image022

from_what can be one of three val­ues:

  • 0 — begin­ning of file (default)
  • 1 — cur­rent posi­tion
  • 2 — end of the file

clip_image023

 

It’s good prac­tice to use the with key­word when deal­ing with file objects, which ensures that the file is closed after its suite fin­ish­es. (this works like the using key­word in C#).

clip_image024

 

To deal with com­plex types (or indeed any non-string types like int) you can use the pick­le mod­ule to con­vert it to and from string.

The process of con­vert­ing a com­plex type to string is called pick­ling.

The process of con­struct­ing a com­plex type from string is called unpick­ling.

clip_image025

 

Exceptions

try-except block:

clip_image001[10]

 

You can han­dle more than one excep­tion if you name them in a tuple:

clip_image002[4]

 

You can han­dle a list of excep­tions in a cer­tain pri­or­i­ty list and if you don’t spec­i­fy a par­tic­u­lar excep­tion type it’ll serve as a wild­card:

clip_image003[8]

 

You can also spec­i­fy a else clause which fol­lows all except claus­es, it’s use­ful for code that must be exe­cut­ed if the try clause does not raise an excep­tion:

clip_image004[4]

The use of the else clause is bet­ter than adding addi­tion­al code to the try clause because it avoids acci­den­tal­ly catch­ing an excep­tion that wasn’t raised by the code being pro­tect­ed by the try-except state­ment.

 

There’s also the option­al final­ly clause which is intend­ed to define clean-up actions that must be exe­cut­ed under all cir­cum­stances:

clip_image005[4]

 

You can get more infor­ma­tion about the instance of the excep­tions:

clip_image006[4]

clip_image007[4]

 

To throw an excep­tion:

clip_image008[9]

 

To re-throw an excep­tion:

clip_image009[4]

 

To define a cus­tom excep­tion:

clip_image010[4]

The __str__() func­tion ensures that you can print the excep­tion instance direct­ly:

clip_image011[4]

 

When cre­at­ing a mod­ule that can raise sev­er­al dis­tinct errors, a com­mon prac­tice is to cre­ate a base class for excep­tions defined by that mod­ule, and sub­class that to cre­ate spe­cif­ic excep­tion class­es for dif­fer­ent error con­di­tions:

clip_image012[4]

 

Some objects define stan­dard clean-up actions, for instance, the with state­ment always clos­es the file after the state­ment is exe­cut­ed:

clip_image013[4]

(the same as the using state­ment in C#)