Learning Python – Part 5

You can become a serverless blackbelt. Enrol to my 4-week online workshop Production-Ready Serverless and gain hands-on experience building something from scratch using serverless technologies. At the end of the workshop, you should have a broader view of the challenges you will face as your serverless architecture matures and expands. You should also have a firm grasp on when serverless is a good fit for your system as well as common pitfalls you need to avoid. Sign up now and get 15% discount with the code yanprs15!


A while back I decided to try and learn Python for the hell of it as it seems like an interesting language and has some of the most concise and user-friendly syntax. Having spent some time going through a number of different learning sources and materials (like the official site python.org which has a very helpful tutorial section) I have put together a set of notes I made as I was learning and hopefully they can be useful to you as a quick list of how-to code snippets.

All the code snapshots I’m showing here are taken from the IDLE Python shell.

Input and Output

The repr() function generates representations that can be read by the interpreter, str() function generates a human-readable of the value:



If an object doesn’t have a particular representation for human consumption, str() will return the same value as repr(), e.g. lists and dictionaries:



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



You can use the string.zfill() function to pad a numeric string on the left with zeros:



You can use string.format() method to format the string output of your code:



You can also use named arguments:



An optional ‘:‘ and format specifier can follow the field name to allow greater control over how the value is formatted:



Passing an integer after the ‘:‘ will cause that field to be a minimum number of characters wide:



For a very long string, you could even reference variables to be formatted by name using a dictionary:


Or you could unpack the dictionary first:



You can use the open() function to get a file object, to open a file for writing:


The first parameter being the file name, the second the mode which can be one of the following:



To open a file and read its contents:



To read one line at a time



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



You can also read x number of bytes at a time:



But remember, you always read starting from the position where your last read finished:



To write to a file:



You can only write string contents to a file, which means you’d need to convert other objects to string first:



To flush the file buffer and actually write them to the file, use the close() function, after which you’ll need to open the file again:



You can use the tell() function to find out your current position in the file:



You can use the seek() function to change the file object’s current position, seek(offset, from_what):


from_what can be one of three values:

  • 0 – beginning of file (default)
  • 1 – current position
  • 2 – end of the file



It’s good practice to use the with keyword when dealing with file objects, which ensures that the file is closed after its suite finishes. (this works like the using keyword in C#).



To deal with complex types (or indeed any non-string types like int) you can use the pickle module to convert it to and from string.

The process of converting a complex type to string is called pickling.

The process of constructing a complex type from string is called unpickling.




try-except block:



You can handle more than one exception if you name them in a tuple:



You can handle a list of exceptions in a certain priority list and if you don’t specify a particular exception type it’ll serve as a wildcard:



You can also specify a else clause which follows all except clauses, it’s useful for code that must be executed if the try clause does not raise an exception:


The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try-except statement.


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



You can get more information about the instance of the exceptions:




To throw an exception:



To re-throw an exception:



To define a custom exception:


The __str__() function ensures that you can print the exception instance directly:



When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:



Some objects define standard clean-up actions, for instance, the with statement always closes the file after the statement is executed:


(the same as the using statement in C#)

Liked this article? Support me on Patreon and get direct help from me via a private Slack channel or 1-2-1 mentoring.
Subscribe to my newsletter

Hi, I’m Yan. I’m an AWS Serverless Hero and I help companies go faster for less by adopting serverless technologies successfully.

Are you struggling with serverless or need guidance on best practices? Do you want someone to review your architecture and help you avoid costly mistakes down the line? Whatever the case, I’m here to help.

Hire me.

Skill up your serverless game with this hands-on workshop.

My 4-week Production-Ready Serverless online workshop is back!

This course takes you through building a production-ready serverless web application from testing, deployment, security, all the way through to observability. The motivation for this course is to give you hands-on experience building something with serverless technologies while giving you a broader view of the challenges you will face as the architecture matures and expands.

We will start at the basics and give you a firm introduction to Lambda and all the relevant concepts and service features (including the latest announcements in 2020). And then gradually ramping up and cover a wide array of topics such as API security, testing strategies, CI/CD, secret management, and operational best practices for monitoring and troubleshooting.

If you enrol now you can also get 15% OFF with the promo code “yanprs15”.

Enrol now and SAVE 15%.

Check out my new podcast Real-World Serverless where I talk with engineers who are building amazing things with serverless technologies and discuss the real-world use cases and challenges they face. If you’re interested in what people are actually doing with serverless and what it’s really like to be working with serverless day-to-day, then this is the podcast for you.

Check out my new course, Learn you some Lambda best practice for great good! In this course, you will learn best practices for working with AWS Lambda in terms of performance, cost, security, scalability, resilience and observability. We will also cover latest features from re:Invent 2019 such as Provisioned Concurrency and Lambda Destinations. Enrol now and start learning!

Check out my video course, Complete Guide to AWS Step Functions. In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. There is something for everyone from beginners to more advanced users looking for design patterns and best practices. Enrol now and start learning!