Running our first script#

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

Prerequisites: you have Python installed, as described in Installing Python on your computer. Alternatively, you can also use MyBinder for this unit. However, you will need a working installation for later exercises.

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 will 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 give them the suffix .py. This suffix is required for Python modules but not mandatory for scripts with a shebang. In general it is 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 gnome-text-editor 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, which can be run from the terminal (python my_file.py).