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 a working python (v3.6) and ipython, as described in the previous chapter.

The standard command-line interpreter

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

$ python
Python 3.6.4 | packaged by conda-forge | (default, Dec 23 2017, 16:31:06) 
[GCC 4.8.2 20140120 (Red Hat 4.8.2-15)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 2
>>> b = 3
>>> print(a+b)
5
>>> a*b
6
>>> a**3
8

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's a feature, of modern interpreted languages. We'll come back to this later.

The default command-line interpreter comes with some functionality (for example, if you use the up and down arrows you can navigate in your previous commands) but this functionality is very sparse. Some important functionalities are missing: some are cosmetic (like colors), some are very useful (like automatic code completion with [TAB] or the possibility to paste several lines of code at once). For all these reasons, the default python command-line interpreter is only used for very small tasks like testing a command or two. Scientists need more interactivity when analysis their data: this is why ipython was created.

ipython: interactive python

ipython is a standard command-line interpreter, but enhanced with many interactive features. Let's open it:

$ ipython
Python 3.6.4 | packaged by conda-forge | (default, Dec 23 2017, 16:31:06) 
Type 'copyright', 'credits' or 'license' for more information
IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: a = 2

In [2]: b = 3

In [3]: print(a + b)
5

In [4]: a*b
Out[4]: 6

What are the differences? The >>> prompt has been replaced by In [1]:. Now there is a slight difference between a line with or without print() (can you find it?). At first sight the differences are small, but it's in the everyday interactive coding that ipython becomes useful.

From now on, we will use the ipython command-line interpreter. Here is a small sample of its most useful functionalities:

Automatic code completion

In ipython, type s and then [TAB]. The tool will give you a list of suggestions to choose from (useful when you forgot how a function was called exactly!). Now type so and [TAB]. Here the only solution will be selected automatically.

Getting help

Type sorted?. A text help should be printed, telling you what this function is about.

Copy paste

Copy the following lines and paste them in your ipython interpreter:

s = 'the jungle book'
print(s)
l = sorted(s)
print(l)
l = ''.join(l)
print(l)

(note that [CTRL-V] doesn't work in a linux terminal - you'll have to use right click -> paste to do so or - even better - use the magical linux middle mouse button)

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 scrip 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 (e.g using gedit), 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

Running a python script from the ipython interpreter

Running a script from the ipython interpreter is as easy as:

In [1]:
%run my_python_script.py
The product of 3 and 6 is 18

(remember the [TAB] functionality in ipython? You can use it on files as well). Running a script this way is different from running a script in the terminal. Indeed, after running the script, the variables defined in it are still available in the current session. Try computing a + b to check it out:

In [2]:
a + b
Out[2]:
9

Importing a python file

Another way to "run" a script in a python interpreter is via the import mechanism:

In [3]:
import my_python_script
The product of 3 and 6 is 18

Although both %run and import execute the script (the output is printed on screen), the two mechanisms are different. As we are going to see next week, the import mechanism is an important feature of the python language (also something which you might not be used to from other languages). import is usually not used as a replacement for %run. The biggest difference with %run is that the variables defined in the script are not available at the command line directly. Instead, they can now be addressed as following:

In [4]:
my_python_script.a * my_python_script.b
Out[4]:
18

... but this is already going too far: more on this next week.

What is this python "interpreter"?

Start with reading the definition from the Tech Terms Dictionary.

Put simple, the python interpreter is a program executing python programs or commands. It reads the programs you write and execute the instructions they contain.

Interestingly, there are more than one implementation of a Python interpreter: indeed, since the python language is well specified (meaning that there are clear rules about which command is supposed to do what), anyone (very) motivated can write a program able to execute a python program. In practice, there aren't that many alternative implementations of the python language, but let's name a few of them:

  • Cpython: the reference implementation of the language (and the one you are using), written in C
  • Jython: a Java implementation, useful to run programs written in both languages
  • PyPy: another implementation aiming at speeding the execution of your programs in certain circumstances.

Question: would it be possible to write a Python interpreter in Python? If yes, what could it be useful for?

We will look into the Cpython interpreter in a little more detail later in the semester, when we will talk about compiled and interpreted languages.

Take home points

  • ipython is short for "interactive python". It's basically the same thing as the default interpreter, but with more features. From now on we will use ipython only: you will learn more of it's features as we go.
  • 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).
  • the import mechanism also "runs" a file, but the way it does so is fundamentally different. We are going to explain the import mechanism in more detail soon.

What's next?