Fore­words

A while back I decided 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-friendly 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­ial sec­tion) I have put together a set of notes I made as I was learn­ing and hope­fully they can be use­ful to you as a quick list of how-to code snippets.

All the code snap­shots I’m show­ing here are taken 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-readable of the value:

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 value as repr(), e.g. lists and dictionaries:

clip_image002

 

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

clip_image003

 

You can use the string.zfill() func­tion to pad a numeric 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 optional ‘:’ and for­mat spec­i­fier can fol­low the field name to allow greater con­trol over how the value is formatted:

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 dictionary:

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 writing:

clip_image011

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

clip_image012

 

To open a file and read its contents:

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 finished:

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 other objects to string first:

clip_image019

 

To flush the file buffer and actu­ally 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 values:

  • 0 — begin­ning of file (default)
  • 1 — cur­rent position
  • 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­ishes. (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 pickle 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

 

Excep­tions

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­ity list and if you don’t spec­ify a par­tic­u­lar excep­tion type it’ll serve as a wildcard:

clip_image003[8]

 

You can also spec­ify a else clause which fol­lows all except clauses, it’s use­ful for code that must be exe­cuted if the try clause does not raise an exception:

clip_image004[4]

The use of the else clause is bet­ter than adding addi­tional code to the try clause because it avoids acci­den­tally catch­ing an excep­tion that wasn’t raised by the code being pro­tected by the try-except statement.

 

There’s also the optional finally clause which is intended to define clean-up actions that must be exe­cuted under all circumstances:

clip_image005[4]

 

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

clip_image006[4]

clip_image007[4]

 

To throw an exception:

clip_image008[9]

 

To re-throw an exception:

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 directly:

clip_image011[4]

 

When cre­at­ing a mod­ule that can raise sev­eral 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­cific excep­tion classes for dif­fer­ent error conditions:

clip_image012[4]

 

Some objects define stan­dard clean-up actions, for instance, the with state­ment always closes the file after the state­ment is executed:

clip_image013[4]

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

Share

Leave a Reply