Learning Python – Part 5


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:



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:



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:



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



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



You can also use named argu­ments:



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:



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



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:


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



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


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



To open a file and read its con­tents:



To read one line at a time



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



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



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



To write to a file:



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



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:



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



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


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



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#).



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.




try-except block:



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



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:



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:


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:



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




To throw an excep­tion:



To re-throw an excep­tion:



To define a cus­tom excep­tion:


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



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:



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:


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