It’s been a while now since I’ve written my first line of Python code. With this blogpost I’d like to share some knowledge, to make it easier for others to get started with Python. I assume you have some basic experience with the command line, and know what unittests are for.
Note: the commands below are written for Mac OSX
Different versions of Python
There are two main versions of Python which are both still frequently used. The most recent version is Python 3, and there is also the older 2.7 version.
Python 2.x is the status quo, Python 3.x is the present and future of the language
On the Python Wiki you can find more information about which Python version to use.
It is common to setup a new environment when you start with a new Python project. The reason for this is that different projects will have different dependencies on other libraries.
You can install all of the dependencies globally, although thats not recommended. Once you switch to an other machine, or if you work in team, you have to make sure all the right version of each external library is installed.
Let’s get started. First of all we install the right tools to set up an environment.
Next we create a new environment named ‘my-environment’, using the command
1 2 3
Now we can create a link to it, so we don’t have to type the full path everytime we want to use the environment.
When you execute
$ my-environment, you can immediately start writing code. Let’s print something to the Terminal with
print "Hello, World!". When you write
2 + 3, you will get
5 as a result.
That’s it, you just evaluated your first two expressions in Python. Now we have our own Python environment where we can install and update all of the dependencies.
Writing your code directly in the Terminal is of course not recommended when you want to write serious programs. Let’s make a project for this environment.
Go to the project folder and create a file named
math.py with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
This is how we write a basic class in Python. It has three methods,
Now we can write some unittests to validate our code. Create a file named
tests.py with the following content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Let’s go through the code step by step.
First of all we import our dependencies.
Math is our own class that we’ve created before.
Next is the class definition for the test. It extends from
Now what follows are the methods. Each one is testing one functionality of our
Math class. We check the return values with
assertTrue and get an exception when these aren’t what we expected.
1 2 3
Finally, we define that if the
tests.py file is executed directly, it has to execute our tests.
That’s it. We can run our code in the Terminal with
$ my-environment tests.py. You should see
Ran 3 tests, which mean your code works as expected.