Installation

You will need to install several pieces of software to get a working Python 3 programming environment. In this section we will install everything that we are going to need in the next few weeks.

There are many ways to write and execute Python code:

Python 3 is available for Windows, Mac and Linux. Python3 alone is often not enough, and you will need to install extra system-specific libraries + editors like Jupyter for Part A of the course and Visual Studio Code for Part B.

To avoid hassles, especially on Win / Mac you should install some so called package manager (Linux distributions already come with a package manager). Among the many options for this course we use the package manager Anaconda for Python 3.8

  1. Install Anaconda for Python 3.8 (anaconda installer may ask you to install also visual studio code, in case accept the kind offer)

  2. If you didn’t in the previous point, install now Visual Studio Code, which is available for all platforms. You can read about it here. Downloads for all platforms can be found here

  3. Now you can read all of Installation on SoftPython EXCEPT:

    • For Mac users: for this course you don’t need to install homebrew, just install Anaconda

    • For everybody: You don’t need to read Projects with virtual environments paragraph (although it’s certainly useful when you have many Python projects on your pc!)

  4. Jupyter and course material format is described in detail in Tools and Scripts on SoftPython, read it!

  5. Finally, you can get familiar with Visual Studio Code by reading what follows. Even if we will use it only in Part B, read it anyway as it’s useful for many development tasks and supports a lot languages.

Visual Studio Code

Visual Studio Code is an Integrated Development Editor (IDE) for text files. It can handle many languages, Python included (python programs are text files ending in .py).

Features:

  • open source

  • lightweight

  • used by many developers

  • Python plugin is not the best, but works enough for us

Once you open the IDE Visual Studio Code you will see the welcome screen:

visual studio code 94j34

You can find useful information on this tool here. Please spend some time having a look at that page.

Once you are done with it you can close this window pressing on the “x”. First thing to do is to set the python interpreter to use. Click on View –> Command Palette and type “Python” in the text search space. Select Python: Select Workspace Interpreter as shown in the picture below.

python interpreter uiu8ue

Finally, select the Python version you want to use (e.g. Python3).

Now you can click on Open Folder to create a new folder to place all the scripts you are going to create. You can call it something like “exercises”. Next you can create a new file, example1.py (.py extension stands for python).

Visual Studio Code will understand that you are writing Python code and will help you with valid syntax for your program.

Warning:

If you get the following error message:

pylint iukj44

click on Install Pylint which is a useful tool to help your coding experience.

Add the following text to your example1.py file.

[1]:
"""
This is the first example of Python script.
"""
a = 10 # variable a
b = 33 # variable b
c = a / b # variable c holds the ratio

# Let's print the result to screen.
print("a:", a, " b:", b, " a/b=", c)
a: 10  b: 33  a/b= 0.30303030303030304

A couple of things worth nothing. The first three lines opened and closed by """ are some text describing the content of the script. Moreover, comments are proceeded by the hash key (#) and they are just ignored by the python interpreter. Please remember to comment your code, as it helps readability and will make your life easier when you have to modify or just understand the code you wrote some time in the past.

Please notice that Visual Studio Code will help you writing your Python scripts. For example, when you start writing the print line it will complete the code for you (if the Pylint extension mentioned above is installed), suggesting the functions that match the letters written. This useful feature is called code completion and, alongside suggesting possible matches, it also visualizes a description of the function and parameters it needs. Here is an example:

code completion j3u34

Save the file (Ctrl+S as shortcut). It is convenient to ask the IDE to highlight potential syntactic problems found in the code. You can toggle this function on/off by clicking on View –> Problems. The Problems panel should look like this

problems ui4i3u4

Visual Studio Code is warning us that the variable names a,b,c at lines 4,5,6 do not follow Python naming conventions for constants. This is because they have been defined at the top level (there is no structure to our script yet) and therefore are interpreted as constants. The naming convention for constants states that they should be in capital letters. To amend the code, you can just replace all the names with the corresponding capitalized name (i.e. A,B,C). If you do that, and you save the file again (Ctrl+S), you will see all these problems disappearing as well as the green underlining of the variable names. If your code does not have an empty line before the end, you might get another warning “Final new line missing”. Note that these were just warnings and the interpreter in this case will happily and correctly execute the code anyway, but it is always good practice to understand what the warnings are telling us before deciding to ignore them!

Had we by mistake mispelled the print function name (something that should not happen with the code completion tool that suggests functions names!) writing printt (note the double t), upon saving the file, the IDE would have underlined in red the function name and flagged it up as a problem.

errors ubgiru

This is because the builtin function printt does not exist and the python interpreter does not know what to do when it reads it. Note that printt is actually underlined in red, meaning that there is an error which will cause the interpreter to stop the execution with a failure. Please remember that before running any piece of code all errors must be fixed.

Now it is time to execute the code. By right-clicking in the code panel and selecting Run Python File in Terminal (see picture below) you can execute the code you have just written.

pythonrun iui575

Upon clicking on Run Python File in Terminal a terminal panel should pop up in the lower section of the coding panel and the result shown above should be reported.

Saving script files like the example1.py above is also handy because they can be invoked several times (later on we will learn how to get inputs from the command line to make them more useful…). To do so, you just need to call the python intepreter passing the script file as parameter. From the folder containing the example1.py script:

python3 example1.py

will in fact return:

a: 10 b: 33 a/b= 0.30303030303030304

Before ending this section, let me add another note on errors. The IDE will diligently point you out syntactic warnings and errors (i.e. errors/warnings concerning the structure of the written code like name of functions, number and type of parameters, etc.) but it will not detect semantic or runtime errors (i.e. connected to the meaning of your code or to the value of your variables). These sort of errors will most probably make your code crash or may result in unexpected results/behaviours. In the next section we will introduce the debugger, which is a useful tool to help detecting these errors.

Before getting into that, consider the following lines of code (do not focus on the import line, this is only to load the mathematics module and use its method sqrt):

[2]:
"""
Runtime error example, compute square root of numbers
"""
import math

A = 16
B = math.sqrt(A)
C = 5*B
print("A:", A, " B:", B, " C:", C)

#D = math.sqrt(A-C) # whoops, A-C is now -4!!!
#print(D)
A: 16  B: 4.0  C: 20.0

If you add that code to a Python file (e.g. sqrt_example.py), you save it and you try to execute it, you should get an error message as reported above. You can see that the interpreter has happily printed off the value of A,B and C but then stumbled into an error at line 9 (math domain error) when trying to compute \(\sqrt{A-C} = \sqrt{-4}\), because the sqrt method of the math module cannot be applied to negative values (i.e. it works in the domain of real numbers).

Please take some time to familiarize with Visual Studio Code (creating files, saving files etc.) as in the next practicals we will take this ability for granted.

The debugger

Another important feature of advanced Integrated Development Environments (IDEs) is their debugging capabilities. Visual Studio Code comes with a debugging tool that can help you trace the execution of your code and understand where possible errors hide.

Write the following code on a new file (let’s call it integer_sum.py) and execute it to get the result.

[3]:
""" integer_sum.py is a script to
 compute the sum of the first 1200 integers. """

S = 0
for i in range(0, 1201):
    S = S + i

print("The sum of the first 1200 integers is: ", S)
The sum of the first 1200 integers is:  720600

Without getting into too many details, the code you just wrote starts initializing a variable S to zero, and then loops from 0 to 1200 assigning each time the value to a variable i, accumulating the sum of S + i in the variable S. A final thing to notice is indentation. In Python it is important to indent the code properly as this provides the right scope for variables (e.g. see that the line S = S + 1 starts more to the right than the previous and following line – this is because it is inside the for loop). You do not have to worry about this for the time being, we will get to this in a later practical…

How does this code work? How does the value of S and i change as the code is executed? These are questions that can be answered by the debugger.

To start the debugger, click on Debug –> Start Debugging (shortcut F5). The following small panel should pop up:

debug 57874y

We will use it shortly, but before that, let’s focus on what we want to track. On the left hand side of the main panel, a Watch panel appeared. This is where we need to add the things we want to monitor as the execution of the program goes. With respect to the code written above, we are interested in keeping an eye on the variables S, i and also of the expression S+i (that will give us the value of S of the next iteration). Add these three expressions in the watch panel (click on + to add new expressions). The watch panel should look like this:

watch 985yhf

do not worry about the message “name X is not defined”, this is normal as no execution has taken place yet and the interpreter still does not know the value of these expressions.

The final thing before starting to debug is to set some breakpoints, places where the execution will stop so that we can check the value of the watched expressions. This can be done by hovering with the mouse on the left of the line number. A small reddish dot should appear, place the mouse over the correct line (e.g. the line corresponding to S = S + 1 and click to add the breakpoint (a red dot should appear once you click).

breakpoint iu54h

Now we are ready to start debugging the code. Click on the green triangle on the small debug panel and you will see that the yellow arrow moved to the breakpoint and that the watch panel updated the value of all our expressions.

step 0 jkjfe34

The value of all expressions is zero because the debugger stopped before executing the code specified at the breakpoint line (recall that S is initialized to 0 and that i will range from 0 to 1200). If you click again on the green arrow, execution will continue until the next breakpoint (we are in a for loop, so this will be again the same line - trust me for the time being).

step 1 kfjjg9

Now i has been increased to 1, S is still 0 (remember that the execution stopped before executing the code at the breakpoint) and therefore S + i is now 1. Click one more time on the green arrow and values should update accordingly (i.e. S to 1, i to 2 and S + i to 3), another round of execution should update S to 3, i to 3 and S + i to 6. Got how this works? Variable i is increased by one each time, while S increases by i. You can go on for a few more iterations and see if this makes any sense to you, once you are done with debugging you can stop the execution by pressing the red square on the small debug panel.

Please take some more time to familiarize with Visual Studio Code (creating files, saving files, interacting with the debugger etc.) as in the next practicals we will take this ability for granted. Once you are done you can move on and do the following exercises.

VS Code - collaborative coding

Visual Studio Code offers a cool way to collaborate in realtime on a project you are working on. Let’s see how to set it up.

1. Install: First make sure you have Live Share Extension Pack installed. It should already be included in VS Code 2019, if not got to extensions and install it:

vsc-folder1

Let’s share some code - as example, we will use a project taken from Object Oriented Programming chapter.

2. open a folder: Once you downloaded the code, open the folder where you put it with File->Open Folder (avoid Open Workspace for simplicity reasons). You should end up with something like this:

CAREFUL ABOUT WHAT YOU SHARE !!!

Once you start sharing, anything in that folder will be accessible and writable by others, we do not want to see your embarassing desktop/home folder !

vsc-folder2

3. Sign in Now you need to sign in, for this we refer to the the official How To

NOTE: in order to share your folder, you will need a Github account, so please if you don’t have it already create one now

4. Share the folder: See the official How To

VS Code - Sharing test runs

In Part B we will also heavily use unit tests (see Unittest tutorial), so it’s a good idea to enabling sharing of test runs by installing Test Explorer Live Share extension:

IT MAY NOT WORK!

It’s often troublesome enough having working tests on your own system, so I expect sharing to be even more problematic. As of Nov 2020, I’ve never tried this thing before, so let’s make a try and if if doesn’t work let’s just use good old screen sharing.

vsc-folder3

[ ]: