Python Programming: A Training Regimen

Welcome to Python Regimen, where I’m going to teach you the ins and outs of Python development… from scratch.

In this first section, we’re going to choose a version, install Python, and then create the obligatory “Hello world” script. If you’re already familiar with Python, feel free to skip ahead to a later sections in the article.

Choosing a Version

There are two versions of Python that are currently being developed:  2.x and 3.x. It’s important to make the right choice, because there are several differences between the two. Once you’ve learned one, it can be a bit annoying to have to transition to the other. In this article, we’ll be working through version 3.3. You may want to go this route in order to follow along with various sections in this series. That said, most things should work with either version. Version two has much more support from third party libraries, whereas version three has more features, and plenty of bug fixes and refinements.

To make things easier, a lot of features that are being added to version three have also being added to version two, so there’s less need to worry about the differences.

Installing the Interpreter

Once you’ve chosen a version, it’s time to install. Download the version of Python for your OS, and run the installer which will get it set up on your machine. There are three ways you can now use Python:

  • Python Shell- lets you run commands line by line.
  • IDLE GUI – lets you write more complex scripts, and run them in one go.
  • Text Editor – any text editor that runs on you system. You can then save it with a .py extension, and run it from the shell.

For now, launch the shell to test if it works correctly. On Windows, navigate to the directory you installed Python. By default, it should be C:\Python33 Once there, launch python.exe. If you’re on Mac or Linux, launch the Terminal, then type python.

I personally find IDLE to be unpleasant to use; so for most of this article, we’re going to be using a standard code editor. If you would rather use an IDE, there are plenty of good ones:

Hello World!

Now we’re all set up; let’s write your first bit of Python!  Go to the shell, type print "Hello World!", and hit enter. The phrase Hello World! should appear.

And that’s it: it really is as simple as that. You’ve written your first Python program! Now is a good opportunity to highlight one of the differences between version two and three: they changed print from a statement to a function. Don’t worry too much about what those words mean for now. All you need to know is that, if you chose to use version three, you need to write print("Hello World!") — the only difference is that you don’t use brackets. We’ll learn about the technical reasons behind this in a future.s


Variables are the first thing you should learn in any new language. You can think of them as named containers for any kind of data. The syntax to declare them is: name = value. You can name anything you like (except for a handful of keywords), and their values can be any type of data.

Data Types

There are many data types, but the following four are the most important:


Numbers can be either integers or floating point numbers.

  • Integers are whole numbers
  • Floats have a decimal point


String are lines of text that can contain any characters. They can be declared with single or double quotes.

You have to escape single and double quotes within the string with a backslash. Otherwise, Python will assume that you’re using them to end the string. Insert line breaks with \n. Python also supports string interpolation using the percent symbol which is deprecated and you should either use .format().

You can access sets of characters in strings with slices, which use the square bracket notation:


Booleans represent either a True or False value. It’s important to note that you have to make the first letter capital. They represent data that can only be one thing or the other. For example:


Lists are used to group other data. They are called Arrays in nearly all other languages. You can create a list with square brackets.

As you can see above, lists may contain any data types, including other lists or nothing at all.

You can access parts of lists just like strings with list indexes. The syntax is the same:

If you nest a list within another list, you can access them with multiple indexes.


Comments are used to describe your code, in the case that you want to come back to it later, or work in a project with someone else.


You’ve seen operators before. They’re those things like plus and minus, and you use them in the same way that you learned in school.

You can also assign the result of an operation on a variable back to the same variable by combining the operator with an equals sign. For example, a += b is a more concise version of a = a + b.

Control Structures

Once you’ve created and manipulated variables, control structures allow you to control the flow of data. The two types we’re learning today are conditionals and loops.


Conditionals allow you to run different blocks of code based on the value of data.


The two types of loops we’re discussing here are for loops and while loops. for loops work using lists, and while loops work using conditions.

while Loops

for Loops


Functions are an important step to cover, when introducing additional complexity into your programming. If a variable is a named container for data, then a function is a named container for a block of code that can be executed on demand. This is useful if you have a program that executes a certain operation lots of times. Instead of copying and pasting the code to do that operation each section where it’s needed, you can simply write one single function to do it for you.

There are two types of functions: the ones that you write yourself and include in your code, and the ones that are included in Python natively, which carry out common procedures, such as converting an integer to a string, or finding the length of a string.

We’re going to look at writing a simple function now, and demonstrate how it can be useful in the real world code. Then, we’ll have a look at some of the most important built-in functions.

A simple Example

Let’s imagine that we want to make a script for a shopping cart that takes the cost of all the items in your cart, and then adds them together to return a total cost. To write a function that would take two costs, add them up, and then print out the output, we might do something like:

To define the function, we need to use the ‘def‘ keyword, and then the name of the function. Next, we type two parentheses (we’ll come back to those later), and then a colon. After that, all of the code that we want to be encased within the function should be indented, just as with ifwhile and for loops.

To make the code in the function run, we type the name of the function, followed by the two parentheses again. If you run this code, you’ll see it print out ’35′, which is the correct output.


That’s great, but at the moment, our functions are a bit rigid – everything about the function is hard-coded into them. For example, let’ say we want to use the sumCart function somewhere else, in a different part of the program, but instead of adding cost1 and cost2 together, we want to add two other costs together that were held in different variables. We’d have to write a whole new function, even though that new function would be exactly the same as the current one, with the names of the variables swapped around – that hardly seems like an efficient solution.

To solve this issue, we use ‘arguments’, and that’s what the parentheses are for. An argument is a way of passing data into a function when we don’t know which variable or variables that data is going to be in. If that’s confusing, let’s take the example that I just referenced. We’ll add two more costs: cost3 and cost4.

Now, we’re going to add two arguments for the two items that we want to add up. Arguments are defined inside the parentheses, and each argument is given a name, with a comma separating each. An argument acts as a temporary reference to the data that you passed in while the function is running.

When we call the sumCart function, the two variables that we’ve passed in (cost1 and cost2) are put into the arguments item1 and item2. This always happens in the same order you define the arguments – in other words, the first variable you pass in is assigned to the first argument, the second to the second argument, and so on for as many arguments as your function takes.

What actually happens when the function is run is that those two arguments are converted into local variables and are assigned the values of the variables that you pass into the function when you call it – in this case the value of cost1 is put into the local variable item1, and the value of cost2 is put into the local variable item2. This means you can easily use them inside the function.

Another way you could look at it is, when you pass a variable as an argument, everywhere that that argument’s name appears in the function, it is replaced with the variable you passed in. So, in this example, everywhere that item1 is written inside the function, it’s replaced with cost1, and the same with item2 and cost2.

To prove that you can pass any numbers you want, if you run this code, you should now receive the sum of cost3 and cost4:

Argument Defaults

Note that a function can accept any number of arguments, but remember: when you call the function, you have to pass it the same number of arguments as you defined, otherwise you will receive an error. There is one way around this: you can define a default value for any argument, which is used in the cases when you don’t supply a value.

Considering our current code, let’s imagine that we want the second item to cost 5 if we don’t give the function a different value. It’s not a likely scenario, but it’ll demonstrate the concept.

If we run this code, you’ll see that, in the first call, the output is 20, which is indeed (cost1 + 5). This doesn’t, however, affect the behavior when both arguments are supplied.

Returning values

There’s one final feature of functions that we’re going to review today: returning values. We’ve learned how to make a function that doesn’t mind what inputs it takes, but what if we wanted to store the answer to ‘totalCost’ in a variable rather than print it out? Perhaps what we want to do is work out the cost of the first two items, and store it in one variable, then do the same with the second two items and store that answer in a second variable. With the current layout of our function, we couldn’t do that in a readable and easy to understand way.

Just like the way we can pass arguments into a function so that we don’t have to hard-code where the data is coming from, we can do the same with the output. I’ll show you with an example – in our previous function, I’m going to replace the word ‘print’ with the word ‘return’:

Obviously, the function is no longer going to print out the answer for us – what it’s going to do instead is pass back the value of the variable totalCost to wherever we called the function from. That way, we can use the answer in whatever context we need to. Now, in our previous program, that wouldn’t be particularly useful, because we didn’t specify anywhere to store it, so I’ve also changed the way we call the function.

We need to provide Python with a variable in which to store the answer, and then we’re simply going to set that variable equal to our statement calling the function. When the function returns a value, that value will now be stored in the variable we specified.

Functions – Built-in

We’ve learned how to make our own functions, and how to use them, but there are some operations that are carried out often enough that Python has included them for use in any program. The way you call them is exactly the same as calling your own, but you don’t have to define them first. We’re going to have a brief look at the most important ones now, but be sure be have a look at the Python documentation because there are loads of useful functions that are available for use, which we don’t have time to cover right now.


First, let’s look at one of the most useful functions in Python: the string conversion function. There are many times in scripting when you have a variable that contains a number, or some other type of data, but you need to convert that value to a string in order to do something with it – normally to print it out onto the screen.

Let’s say we have a number in a variable, and that we want to print it out, with the message ‘The number is ‘ and then the number. If we write:

…then we’re going to encounter an error, because what you’re asking Python to do is to add a number and a string together – which doesn’t really make a whole lot of sense. What we need to do is to convert the number 10 into the string 10. If we do that, Python will understand that what we’re trying to do is not find a sum, but instead concatenate the two strings into one.

This is where the str function comes in. It accepts a value, and returns a string to represent it. In the case you pass it a number, it will simply return the number but in string format.

Now that we’ve encased the number in a string conversion function, the code runs perfectly. The str function doesn’t have to take a number though – it can also take other values, such as a Boolean:

The str() function finds the closest string match it can find for the value of ‘true’ and returns it, meaning that we can output it nicely.


Another common task for strings is to be able to find the length of them, and, again, Python has a built in function for this. Let’s take the string ‘Hello World’ and try to find its length. To do this, we’re going to need the built-in len() function, which stands for length. All we need to do is pass it the string we want to use, and it will return the number of characters in it:

The len() function is capable of more than this, though. What it actually does is count the number of items in the object you give it – if you give it a string then that’s the number of characters, but you can also give it a list or a tuple, for example, and it will return the amount of items in that particular object.


Moving on, often you are given a number like 10.6 or 3.896, which is not an integer, but you need an integer from them. The built-in function to convert to an integer is called int(), and it works fairly predictably. The function will return the integer conversion of that number. Note that this function does NOT round the input to the nearest integer – it very simply throws away anything after the decimal point and returns the number to you. So the input of 10.6 will return 10, NOT 11. Similarly, 3.25 would return 3.

The int function can also convert a string to an int data type. For example, given this, the output would still be 10:

However, be careful, because, when it is converting from a string to an integer, int() will NOT deal with decimal places. If you provide it:

Then it will throw an error, because the input wasn’t an integer, so it didn’t know how to handle it.


Finally, we’re going to quickly look at the range() function; it comes up surprisingly often when you start doing more complex tasks in Python, and, while it might not seem massively useful at the moment, it’s worth having a look at and getting to know how it works. Range is a function that you use to create a list of numbers following a certain pattern. The simplest example is that perhaps you need a list containing all of the numbers 0 to 10. Instead of typing them out manually, you can use the range function to do it in one line.

Range accepts an integer as the parameter, and, in this case, we’ll pass it 11. The function then starts at zero, and makes a list counting upwards until it hits one less than the number you put in. So here, if we put in 11, it will store the numbers 0 – 10 in the list numbers:

What if we wanted to print the numbers five to ten instead? Well, optionally, we can include another argument for the starting number, so this will print the numbers five to ten:

Lastly, what if we wanted to print only the odd numbers under 10? Well, range accepts a third value, which is the amount to go up each step. So if we start at 1, set the step to two and the upper limit to 11, we should end up with all the odd numbers under ten:

As a final note, any of these numbers can be negative as well, so if we wanted to count DOWN from 10 to 1 instead of up, we could set the step to be negative 1, the starting value to 10 and the limit to 0, like so:

Note that range will only deal with integers, so make sure that you don’t give it any values that aren’t integers or you’ll throw an error.


Alright, we’ve now covered functions; let’s move on to the next topic of today’s article: modules. If functions are groups of code, then modules are groups of functions. There’s more to them, but that’s a good way of thinking about them for now.

As we discussed earlier, you can’t make a complex program without sorting code into functions, and as your program continues to grow further, even they become unwieldy. You have to sort them into another hierarchical level. These are modules. So we can summarize them as a structural and organizational tool for our code.

Modules are quite easy to create. They are simply Python files, like your regular scripts. To create a module, write one or more functions in a text file, then save it with a .py extension. Let’s do that now with an example. Open up a new file your text editor or IDE, and make a function. I’m going to continue with the example of a shopping cart from earlier and make a function to calculate tax on the products.

Create a new file in your IDE or text editor and let’s create a function for calculating tax on a product.

If we save this file with a .py extension in the same directory as our other script, we can use it as a module! It’s important to give it a descriptive name so you know what it does when you come back later, so call this one finance.py.

Importing modules

To use modules, we can use either the import or the from keyword. import is the simplest and most common, so let’s try that first. You then specify the name of the module, which is simply the filename, without the .py extension. For example, with our finance module in the same folder as our script, we could write:

…and we would have access to all the functions in the script. We can then call them just as we did before. You can also use the from keyword, which allows you to select specific functions from the library, if you know which ones you require beforehand. For a module that has hundreds of functions, this is recommended – it saves loading time on functions that aren’t even being used.

You can import several by separating their names with commas.

And you can even use the asterisk wildcard to import everything.

After importing the module, to use the functions contained within it, you use the module name, followed by a dot, and then the function name.

This should result in 105 when the script is run. A simple result, but it means you’ve got a working function!

Built-in Modules

There are plenty of built in modules, just as there are with built in functions. This is where Python really excels! It takes what’s called the “batteries included” approach.

Because Python has such an extensive range of built-in modules, there’s no way to cover them all in one lesson. Some are quite obscure, and there’s no point teaching a load of information you might never have a use for. Instead, let’s cover several of the most useful ones.


A good one to start with is random , because it’s easy to understand and useful in most scripts you’ll write. As you’d expect, this module lets you generate random numbers. For example, when using Python to create a website, they can be used in making your password database more secure or powering a random page feature. If we wanted a random integer, we can use the randint function, like so:

This will output either 1, 2, 3, 4 or 5. Randint accepts exactly two parameters: a lowest and a highest number. As you can see, it includes the highest number but goes from 1 above the lowest number. If you want a random floating point number, you can use the random function:

…which outputs a random number between 0 and 1, to a load of decimal places. If you want a larger number, you can multiply it. For example, a random number between 0 and 100:

The random module also has a function for choosing a random element from a set such as a list, called choice.


The math module provides access to mathematical constants and functions.

There are lots more functions in the module, but these are some of the most useful. You can find a full list here.


If you need to work with dates and times, then the datetime module is your friend. This one is a very useful one to know about for web development. If you’re making an website with comments, or a blog, then you’ll probably be displaying their age, or the time they were created.

Let’s import the module as usual:

For convenience, you can also import the date and the time components separately, so you don’t have to type as much later.

Let’s have a look at some of the functions it provides:

There are some useful functions for converting dates into useable strings. strftime allows you to format a string based on special characters preceded by a percent symbol. %d represents day, for example:


The next module we’re looking at is os, which provides functions that allow you to interface with the underlying operating system that Python is running on – be that Windows, Mac or Linux. We’ll focus on the path submodule. It allows you to manipulate and find the properties of files and folders on the system, so it’s the most useful for web development. You’ll often need to manage files, for example user uploads:

These timestamps can be converted to useable strings using the datetime module – you can see how you can combine modules.

The last function in the os module we’re going to look at is join. It combines two paths into one. You might be thinking: “Why can’t I just concatenate the strings?”, but it’s not as simple as that. On Windows, the path delimiter is a backslash, on Mac and Linux it’s a forward slash. This module alleviates problems like that and makes sure your Pythons scripts work on any system.


To finish our tour of Python’s standard library, we’re going to have a brief look at urllib. This module lets you interface with the web, so it’s obviously quite relevant to us. The most useful function it provides is urlopen, which downloads a page.

You can obviously swap the URL string for any site. This will download the HTML content of the page. This won’t return a string though, so we need to read the data to get that out:

This will return the first 100 characters of the HTML source of Pypix. Once you have this data, you can sort through it and extract the necessary bits that you require.


If your module is in a different directory than your script, it’s a bit trickier to import them. You have to create a file that tells Python the folder is a package. For example, if you have a folder, called subdirectory, in the same folder as your script, and then your module within that subdirectory, you would have to create a file called __init__.py in the same folder as the module. This file can be empty. Then, from your script, you’d import it:

%review it if you need a refresher!

Object Oriented Programming

Python is primarily designed as an object-oriented programming language – but what does ‘object oriented’ actually mean?

There are a variety of definitions for the term, and you could talk for literally hours trying to explain the complicated ins and outs, nuances and differences in implementations, but I’ll try to give a quick overview.

Broadly, object oriented programming is the concept that, in programming, the objects that we’re manipulating are more important than the logic needed to manipulate those objects. Traditionally, a program has been seen as a recipe – a set of instructions that you follow from start to finish in order to complete a task. That can still be true, and for many simple programs, that’s all which is required. That approach is sometimes known as procedural programming.

OOP puts objects at the center of the process.

On the other hand, as programs get more and more complex and convoluted, the logic needed to write them in a purely procedural way gets more and more twisted and hard to understand. Often object oriented approaches can help with that.

When we talk about object oriented approaches, what we do is put the objects at the center of the process, instead of simply using them as necessary containers for information as part of our procedural instructions. First, we define the objects we want to manipulate and how they relate to each other, and then we start to flesh it out with logic to make the program actually work.

When I talk about ‘objects’, I can be talking about all sorts of things. An ‘object’ can represent a person (as defined by properties such as name, age, address etc.), or a company (as defined by things like number of employees and so on), or even something much more abstract, like a button in a computer interface.

In this introduction, we’re not going to be covering all of the concepts in this topic because we’d be here all night, but by the end of the tutorial, I hope you’ll have a solid understanding of the principles you need to start straight away using some simple object-oriented techniques in your Python programs. Even better, these concepts are fairly similar in a lot of programming environments. The knowledge transfers over from language to language quite nicely.

Refer this article for more detailed overview of OOP.

Getting Started

I mentioned earlier that the first thing we should do when we’re going for an OOP approach is to define the objects we’re going to be using. The way we do this is to first define the properties that it possesses using a class. You can think of a class as a sort of template; a guide for the way an object should be structured. Each object belongs to a class and inherits the properties of that class, but acts individually to the other objects of that class.

An object is sometimes referred to as an ‘instance’ of a class.

As a simple example, you might have a class named ‘person’ with, say, an age and a name property, and an instance of that class (an object) would be a single person. That person might have a name of “Andy” and an age of 23, but you could simultaneously have another person belonging to the same class with the name of “Lucy” and an age of 18.

It’s hard to understand this without seeing it in practice, so let’s get some actual code going.

Defining a class

To define a class, in typical simple Python fashion, we use the word ‘class,’ followed by the name of your new class. I’m going to make a new class here, called ‘pet’. We use a colon after the name, and then anything contained within the class definition is indented. However, with a class, there are no parentheses:

So now we’ve got a class, but it’s rather useless without anything in it. To start, let’s give it a couple of properties. To do this, you simply define some variables inside the class – I’m going to go with the number of legs to start with. As usual, you should always name your variables so that it’s easy to tell what they are. Let’s be original and call it ‘number_of_legs’. We need to define a value or we’ll get an error. I’ll use 0 here (it doesn’t matter too much in this case since the number of legs will be specific to each instance of the class – a fish doesn’t have the same amount of legs as a dog or a duck, etc. – so we’ll have to change that value for each object anyway).

Instances and member variables

A class on its own isn’t something you can directly manipulate; first, we have to create an instance of the class to play with. We can store that instance in a variable. Outside of the class (without any indentation), let’s make an instance of the class and store it in the variable, ‘doug’. To make a new instance of a class, you simply type the name of the class, and then a pair of parentheses. At this point, there’s no need to worry about the parentheses, but later on you’ll see that they’re there because, like a function, there’s a way of passing in a variable for use by the class when you first create the instance.

A class on its own isn’t something that you can directly manipulate.

Now that we have an instance of a class, how do we access and manipulate its properties? To reference a property of an object, first we have to tell Python which object (or which instance of a class) we’re talking about, so we’re going to start with ‘doug’. Then, we’re going to write a period to indicate that we’re referencing something that’s contained within our doug instance. After the period, we add the name of our variable. If we’re accessing the number_of_legs variable, it’s going to look like this:

We can treat that now exactly as we would treat any other variable – here I’m going to assume doug is a dog, and will give that variable the value of 4.

To access this variable, we’re going to use it again exactly as we would treat any other variable, but using that doug.number_of_legs property instead of the normal variable name. Let’s put in a line to print out how many legs doug has so that we can show that it’s working as it should:

If you run the code above, you’ll see that it’s printed out for us. It defined our ‘pet’ class, created a new instance of that class and stored it in the variable ‘doug’, and then, inside that instance, it’s assigned the value of 4 to the number_of_legs variable that it inherited from its class.

So you can see from that very simplified example how you can begin to build nice, modular data structures that are clear and easy to use, and can start to scale quite nicely.

Introducing Logic

Okay, so that’s the very basics of classes and objects, but at the moment we can only really use classes as data structures – or, containers for variables. That’s all well and good, but if we want to start performing more complex tasks with the data we’re manipulating, we need a way of introducing some logic into these objects. The way we do that is with methods.

Methods, essentially, are functions contained within a class. You define one in exactly the same way as you would a function, but the difference is that you put it inside a class, and it belongs to that class. If you ever want to call that method, you have to reference an object of that class first, just like the variables we were looking at previously.

Methods, essentially, are functions contained within a class.

I’m going to write a quick example here into our pet class to demonstrate; let’s create a method, called ‘sleep’, which is going to print out a message when it’s first called. Just like a function, I’m going to put ‘def’ for ‘define’, and then I’m going to write the name of the method I want to create. Then we’re going to put our parentheses and semicolon, and then start a new line. As usual, anything included in this method is going to be indented an extra level.

Now, there is another difference between a method and a function: a method always, always, always has to have an argument, called ‘self’ between the parentheses. When Python calls a method, what it does is passes the current object to that method as the first argument. In other words, when we call doug.sleep(), Python is actually going to pass the object ‘doug’ as an argument to the sleep method.

We’ll see why that is later, but for now you need to know that, with a method, you always have to include an argument called ‘self’ first in the list (if you want to add more arguments, you can add them afterwards, exactly like if you were passing multiple arguments to a function). If you don’t include that argument, when you run the code, you’re going to get an error thrown because Python is passing in an argument (this ‘self’ object), and the method is saying, ‘Hey, man, I don’t take any arguments, what are you talking about?’. It’s the same as if you tried to pass an argument into a function that doesn’t accept any arguments.

So here’s what we have so far:

Inside this method, we’re going to write a print statement like so:

Now, if we want to use this method, we simply use an instance of the pet class to reference it. Just like the number_of_legs variable, we write the name of the instance (we’ve got one called doug), then a period, then the name of the method including parentheses. Note that we’re calling sleep using no arguments, but Python is going to add in that argument by itself, so we’re going to end up with the right amount of arguments in total.

If you run this code, you should see that it prints out the message we wrote.


Great, so now how about we write a new method to print out how many legs the pet has, to demonstrate how you can use methods to start manipulating the data within the class, and to demonstrate why we need to include this confusing ‘self’ argument. Let’s make a new method, called ‘count_legs’.

This is where the ‘self’ argument comes in. Remember when we were accessing number_of_legs from outside the class and we had to use ‘doug.number_of_legs’ instead of just ‘number_of_legs’? The same principle applies; if we want to know what is contained in that variable, we have to reference it by first specifying the instance containing that variable.

However, we don’t know what the instance is going to be called when we write the class, so we get around that using the ‘self’ variable. ‘self’ is just a reference to the object that is currently being manipulated. So to access a variable in the current class, you simply need to preface it with ‘self’ and then a period, like so:

In practice, what this means is that wherever you write ‘self’ in your method, when you run the method that self is replaced by the name of the object, so when we call ‘doug.count_legs()’ the ‘self’ is replaced by ‘doug’. To demonstrate how this works with multiple instances, let’s add a second instance, representing another pet, called ‘nemo’:

This will print out a message for 4 and then 0 legs, just as we wanted, because when we call ‘nemo.count_legs(),’ the ‘self’ is replaced by ‘nemo’ instead of ‘doug’.

In this way, our method will run exactly as intended because the ‘self’ reference will dynamically change depending on the context and allow us to manipulate the data only within the current object.

The main things you need to remember about methods is that they’re exactly like functions, except that the first argument has to be ‘self’ and that to reference an internal variable you have to preface the variable name with ‘self’.

Just as a note: You can actually use any name instead of ‘self’ for your methods. –The methods here would work just as well if we renamed the variable ‘self’ to any word. Using the name ‘self’ is simply a convention which is useful to Python programmers because it makes the code much more standard and easy to understand, even if it’s written by someone else. My advice would be to stick to the conventions.

Some More Advanced Features

Now that we’ve gone over the basics, let’s have a look at some more advanced features of classes, and how they can help make your programming easier to structure.

The next thing we’re going to talk about is inheritance. As its name might hint, inheritance is the process of making a new class based around a parent class, and allowing the new class to inherit the features of the parent class. The new class can take all of the methods and variables from the parent class (often called the ‘base’ class).

Inheritance is the process of making a new class based around a parent class.

Let’s extend our pet example to see how this might be useful. If we use ‘pet’ as our parent class, we could create a child class which inherited from the pet class. The child class might be something like ‘dog’, or ‘fish’ – something that is still a ‘pet’, but is more specific than that. A dog is a pet, and does the same things that all pets do – for example it eats and sleeps and has an age and a number of legs – but it does other things that are specific to being a dog, or at least more specific than to being a pet: dogs have fur, but not all pets do. A dog might bark, or fetch a stick, but not all pets would.

Getting back to the point, say we wanted to make a class in our program to represent a dog. We could use inheritance to inherit the methods and variables contained in ‘pets’ so that our dog could have a ‘numberOf Legs’ and the ability to ‘sleep’, in addition to all the dog specific things we might store or do.

Now, you might be wondering why we don’t put those methods and variables into the dog class and get rid of the pet class entirely? Well, inheritance gives us two distinct advantages over that approach: One, if we want an object that is a pet, but isn’t a dog – a generic pet, if you will – we can still do that. Two, perhaps later we want to add a second type of pet – maybe a fish. We can make that second class also inherit from pet, and so both classes can share everything in pet, but at the same time have their own more specific methods and variables that apply only to that type of object.

We’re getting a little bogged down in the theory here, so let’s write something to make it a little clearer. First, we’re going to write a new class, called ‘dog’, but this time, between the class name and the colon, we’re going to put some parentheses, and in them, we’re going to write the name of the class that we want to inherit from, sort of as if we’re passing this new class an argument, like we would a function.

Next, let’s give this class a simple method to demonstrate how it works. I’m going to add a ‘bark’ method which will print ‘woof’:

So, now let’s see what happens if we make an instance of this class. I’’m going to call our new dog ‘doug’ again. Now, if we call doug.bark():

As expected, doug barks. That’s great, but we haven’t seen anything new yet – just a class with a method. What inheritance has done for us, though, is to make all of the pet functions and variables available to us through our ‘doug’ object, so if I do something like this:

Then the sleep method will also execute correctly. In effect, our doug object belongs to both the ‘pet’ AND the ‘dog’ class. To ensure that the variables do the same as the methods, let’s try this:

You can see that doug acts exactly as before, showing that our variables are being inherited. Our new child class is simply a specialized version of the parent one, with some extra functionality but retaining all of the previous functionality.

Create a Dynamic Website

We’ve covered quite a bit of Python in the previous sections in this article. Now, we’re going to combine everything we’ve learned so far to build a dynamic website with Python.

So, how do you get started creating websites with Python? Well, you could do it all yourself, and write a program that runs on a web server, accepting page requests and serving up responses in the form of HTML and other resources. However, that’s a lot of work, so why go to all the trouble when there are plenty of existing tools out there to do the job for you? These tools are called frameworks, and they’re what we’ll use today to create our website.

Python Frameworks

There are quite a few Python web frameworks, but here are some of the best:

  • Django – We’re going to use this today. It has a huge set of features, but remains simple to use. The documentation is also excellent, so if you get stuck, you’ll have the easiest time solving your problem with Django.
  • Grok – Another framework with a feature set that comes close to Django. If you decide you don’t prefer Django, this is a good alternative.
  • WebPy – A much more lightweight framework. It doesn’t have as many features, though it did power Reddit for a period of time!
  • TurboGears – Though previously having a reputation for poor documentation, TurboGears has improved substantially in the last year.

A more comprehensive list can be found on the Python website if you’re in need of additional options. Today we’re going to set Django up for development on a local machine, and then build a simple blog. We’re also going to review the process of installing it on a remote web server.

Installing Django

We’ll be performing most of our work today in the Terminal. This should all work on Mac and Linux; however, if you’re running Windows, the process is somewhat different. A familiarity with the command line isn’t necessary if you’re only writing Python, though, if you’re planning on using Django, or running a dynamic website in general, it’s worth learning.

Refer Django docs for Installation.

Once Django is installed. Let’s test it out.

You should see ’1.6.1′. If you do, everything worked and Django is installed on your system. Congratulations! We’re ready to begin creating our site!

Building our Blog

We’re going to build a blog system today, because it’s an excellent way to learn the basics. First, we need to create a Django project.

What do each of these files do?

  • __init__.py tells Python that this folder is a Python package. We learned about these in the third lesson; it allows Python to import all of the scripts in the folder as modules.
  • manage.py isn’t actually part of your website; it’s a utility script that you run from the command line. It contains an array of functions for managing your site.
  • settings.py contains your website’s settings. Django doesn’t use XML files for configuration; everything is Python. This file is simply a number of variables that define the setting for your site.
  • urls.py is the file that maps URLs to pages. For example, it could map yourwebsite.com/about to an About Us page.


However none of these files on their own make a functional website. For that, we need Apps. Apps are where you write the code that makes your website function, but before we take a look at them, we need to understand a bit about Django’s design principles.

First, Django is an MVC framework, which stands for Model View Controller. Django refers to itself an MTV framework, which stands for Model Template View. It’s a slightly different approach than MVC, but fundamentally, they’re quite similar. Anyhow, MVC is an architectural pattern that provides a method for structuring your projects. It separates the code that’s used to process data from the code that manages the user interface.

Django subscribes to the DRY, or “Don’t Repeat Yourself” philosophy.

Secondly, Django subscribes to the DRY, or Don’t Repeat Yourself philosophy, which means that you should never be writing code that performs a certain task more than once. For example, in our blog, if we wrote a feature that picked a random article from the archive, and implemented this feature on multiple pages, we wouldn’t code it again each time it was needed. We’d code it once and then use it on each page.

So how does this relate to apps? Well, apps allow you to write your website in a DRY style. Each project, like the one we have here, can contain multiple apps. Conversely, each app can be part of multiple projects. Using the example from earlier, this means that if we made another site in the future that also needed a random page feature, we wouldn’t have to write it all over again. We could simply import the app from this project. Because of this, it’s important that each app serves one distinct purpose. If you write all the functionality of your site within one app, and then need to use part of it again later, you have to import it all. If you were making an eCommerce website, for example, you wouldn’t want to import all the blog features. However, if you make one app for the random feature and one app for the blog publishing system, you could pick and choose the bits that you require.

This also means that within the site, the code is well organized. If you want to alter a feature, you don’t have to search through one massive file; you can instead browse to the relevant app and change it without worrying about interfering with anything else.

Again, we’ve got an __init__.py file to make it a package, and three other files: models, tests and views. We don’t need to worry about tests for now, but the other two are important. Models and Views are the and V parts of MVC.

In models, we define our data structures.

If you’ve ever worked with PHP before, you might have used PhpMyAdmin to create your MySQL tables, and then written out your SQL queries manually in your PHP scripts. In Django, it’s much easier. We define all the data structures we need in this models file, then run a command and all the necessary databases are made for us.

When you wish to access that data, you go via these models by calling method on them, instead of running raw queries. This is very helpful, because Django can use several database programs. We’re going to use MySQL today, because it’s the most powerful, and is what most hosts provide, but if we needed to switch to a different database in the future, all of the code will still be valid! In other languages, if you wanted to switch to SQLite or something similar, you would need to rewrite the code that accesses your database.

In the views file, we write the code that actually generates the web pages. This ties all the other parts together. When a user types in a URL, it is sent by the urls script we saw earlier to the views script, which then gets relevant data from the models, processes it and passes it into a template, which finally gets served up as the page the user sees. We’ll take a look at those templates shortly. They’re the easiest part – mostly HTML.

For a blog, we’ll need a table of posts, with several fields for the title, body text, author, the time it was written, and so on. A real blog would have comments, but that’s beyond the scope of today’s demo.

You need to change the database settings first. These begin on line twelve.

If you try to run the server, it should work, provided that you successfully installed MySQL. If you visit in your web browser, you should see the default Django page.

Now let’s turn our Django site into a blog. First, we need to use our Models to create tables in the database by running the following command:

Every time you change your models, you should run this command to update the database. Note that this can’t alter existing fields; it may only add new ones. So if you want to remove fields, you’ll have to do that manually with something like PhpMyAdmin. Because this is the first time we’ve run the command, Django will set up all the default built in tables for things like the administration system. Just type ‘yes’ and then fill in your details.

Now let’s set up the urls.py file. Uncomment the first line in the examples section, and change it to say url(r'^$', 'blog.views.home', name='home').

Now, let’s create the views file to respond to these requests.


This index.html file doesn’t exist yet, so let’s make it. Create a folder, called templates in the root directory and save a file in it called index.html, which can simply contain “Hello World” for now. Then, we need to edit the settings file so Django knows where this template is located.

Line 105 is where the section for declaring template folders starts; so adjust it, like so:

If you run the server again and refresh the page in your browser, you should see the “Hello World” message. We can now begin laying out our blog. We’ll add some boilerplate HTML for the home page.

If you save and refresh the page, you should see that the page has been updated with this new content. The next step is to add dynamic content from the database. To accomplish this, Django has a templating language that allows you to embed variables with curly braces. Change the middle section of your page to look like this:

We can then pass in values to these variable placeholders from the views.py file by creating a dictionary of values.

Save and refresh, and you should see that you’re now passing in content to a template from your views file. The final step is to get data from our database and pass that in instead. Luckily, we can do this all without SQL queries, using Django’s models. We need to add our blog app to our FirstBlog project by changing another setting. Go to INSTALLED_APPS on line 112, and add the

to the list.

Then change views.py so it adds data from the database.

Next, update the template to access this data.

Here, we can access all the data in our table in the views.py file, then select only the first ten entries. We pass this data into the template, loop through the entries and display the data with the HTML of our site. This won’t work just yet, because there’s nothing in the database. Stop the server and run:

Django’s Admin System

The last thing we need to do today is review Django’s administration system. This is a really powerful feature of Django that lets you manage your site without writing any more code, as you would have to if you were creating a site from scratch. To enable it, we need to change a few settings. First, uncomment lines 4, 5, 13 and 16 within urls.py, so that you can actually access the admin page. Next, go to the INSTALLED_APPSsection of settings.py and uncomment 'django.contrib.admin', and'django.contrib.admindocs',. To let the admin control your posts table, create a new file calledadmin.py in the blog folder, and add the following lines:

Run python manage.py syncdb again to add the tables for the admin section, and restart the server.

If you visit now in your browser, you should see a login page. Use the details you chose earlier when you first ran the syncdb command to log in. You should see a section, called Blog, with a subtitle for the posts table. You can use this to create, edit and remove blog posts with a simple interface.

That’s all there is to do. You’ve just created a fully functioning, albeit simple, blog. To finish this lesson, we’re going to look at installing Django on a web server.

Installing on a Web Server

There are two types of web hosting, and which one you have will affect whether you can use Django. If you have shared hosting, you’re entirely at the mercy of your host.

Many cheap web hosts don’t support Python. While PHP is nearly guaranteed, support for other languages often isn’t. You’ll have to check the control panel to determine if Python (and Django) are available. Obviously the process is slightly different with every host. Almost all hosting runs on Apache, and we can use it to host Django, using the mod_wsgi or mod_python Apache modules.

Most web hosts run scripts in several languages using CGI. Django can run on FastCGI, and also, theoretically, on CGI, but this is not officially supported and would be far too slow for an actual production website. You’ll need to check if these are installed. They’re usually found under a heading, like “CGI and Scripting Language Support”.

If you have VPS hosting, or are lucky enough to have a dedicated server, your life is much easier. Usually these come with Python preinstalled, and from there, you only need to follow the same steps we went through to get a local copy of Django running. If you don’t have Python, you can install it with a package manager. Your system may even come with Django.

Once you’ve installed Django on your server, upload the site you just made using any file transfer client. You can put the files anywhere, but keep them out of the public folder, or anyone will be able to see the source code of your site. I use /home for all my projects.

Next, create a MySQL database, called ‘firstblog’ on your server and run syncdb again. You’ll have to create your account for the admin control panel again, but this is a one-time thing.

If you try and run this, you might receive an error, and that’s because the settings for the server are different those on your local computer. You may need to change the database password within settings.py, but depending on your server configuration, you may also encounter other issues. Google is your friend in these situations!

To run the server this time, the command is slightly different. You have to specify an IP address and port so that you can access the site over the internet.

If you visit your site in a web browser, on port 8000, you should see your site!


As always, I’m happy to discuss any questions about this tutorial or Python in general within the comments. Thanks for reading.

  • Craig Belpedio

    I love the guide, but I just want to clarify that PyCharm is cross-platform. It runs on Windows, OS X, and Linux. I just don’t want anyone left out because it’s such a great tool!

    • Bartosz Nowak

      The moment i read ” PyCharm (Windows) ” i scrolled down to say it runs on Linux as good as on Windows (on Mac probably too, didn’t try it though), but hey, you where first ;)

  • Mark Lawrence

    Why not tell people using Python 2 to use from __future__ import print_function at the top of their scripts or interactive sessions and then they will automatically get used to using print(‘something’)?

  • jmafc

    “There are two versions of Python that are currently being developed: 2.x and 3.x.”

    Actually, only Python 3.4 is being developed, as in “new work done and new features added”, whereas Python 2.x (specifically 2.7) and Python 3.1-3.3 are only being maintained.

  • Frank

    Damn, one of the first examples doesnt work for me as expected:
    “numbers = range(11)
    It just prints “range(11)”, but I’m/you are expecting some numbers… Im using Python 3.3.3, what am I doing wrong ?

    • jgmitzen

      This looks like the example was written with Python 2.x in mind. In Python 3 range is a generator and does not return a list. To print out the numbers, you need to do one of two things:

      numbers = list(range(11))



  • PeacePoll

    In your examples, like name = value., you use a trailing period. If I were approaching this as a novice, I would assume the period is a statement terminator.

  • satoshideath

    Damn, this is such a good guide. A great overview of Python.