Getting started with Python#

In this chapter we are getting used to the python command line, and we are going to write our first small program.

Prerequisites: you have python and ipython installed, as described in Installing Python on your computer. Alternatively, you can also use MyBinder for this unit.

The standard command-line interpreter#

Let’s open a python interpreter and type in some commands:

>>> a = 2
>>> b = 3
>>> print(a+b)
5
>>> a*b
6
>>> a**3

This should look quite familiar to you, whatever language you learned before. We defined variables, and did some arithmetics with them. On line 3 we used the print() function to display the output of our computations, but as it turns out it is not necessary: the command line shell will print the output anyway. This functionality is called REPL, and it is a feature of modern interpreted languages. We’ll come back to this later.

Running scripts#

Of course, the command-line interpreter is only useful for small tasks or for data exploration. Most of the time, you will want to write scripts (a collection of commands executed in order to reach a certain goal) or more complex programs (the difference between “scripts” and “programs” is fuzzy, but for now let’s call a “program” a tool which involves writing several functions and/or files).

Running a python script from the terminal#

Python scripts are simple text files. Per convention we like to give them a suffix: .py. This suffix is required for python modules but not mandatory for scripts with a shebang. In general it’s a good idea to use the .py suffix though.

Let’s create a new file, my_python_script.py (using a text editor of your choice, for example gedit in ubuntu or wordpad in Windows), and add these few lines of code to it:

a = 3
b = 6
c = a * b
print('The product of {} and {} is {}'.format(a, b, c))

Now you should be able to run the script by calling python in a terminal:

$ python my_python_script.py

Take home points#

  • python scripts are text files ending with .py. They can be run from the terminal (python my_file.py) or from the ipython interpreter (%run my_file.py).