Introduction solutions

Download exercises zip

Browse files online

In this practical we will set up a working Python3 development environment and will start familiarizing a bit with Python.

There are many ways to write and execute Python code:

  • Python tutor (online, visual debugger)

  • Python interpreter (command line)

  • Visual Studio Code (editor, good debugger)

  • Jupyter (notebook)

  • Google Colab (online, collaborative)

During this lab we see all of them and familiarize with the exercises format. For now ignore the exercises zip and proceed reading.

Installation

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

Python3 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 Visual Studio Code and Jupyter.

Windows/Mac installation

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.7.

  1. Install Anaconda for Python 3.7 (anaconda installer will ask you to install also visual studio code, so 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

Linux installation

Although you can install Anaconda on Linux, it is usually better to use the system package manager that comes with your distribution.

  1. Check the Python interpreter - most probably you already have one in your distribution, but you have to check it is the right version. In this course we will use python version 3.x. Open a terminal and try typing in:

python3

if you get an error like “python3 command not found” , try typing

python

if you get something like this (mind the version 3):

console 43432i

you are already sorted, just type Ctrl-D to exit. If it doesn’t work, try typing exit() and hit Enter

Otherwise you need to install Python 3.

Linux, debian-like(e.g. Ubuntu)

Issue the following commands on a terminal:

sudo apt-get update
sudo apt-get install python3

Linux Fedora:

Issue the following commands on a terminal:

sudo dnf install python3
  1. Install now the package manager pip, which is a very convenient tool to install python packages, with the following command (on Fedora the command above should have already installed it):

    sudo apt-get install python3-pip

    Note:

    If pip is already installed in your system you will get a message like: python3-pip is already the newest version (3.x.y)

  2. Install Jupyter notebook:

Open the system console and copy and paste this command:

python3 -m pip install --user jupyter -U

It will install jupyter in your user home.

  1. Finally, install Visual Studio Code. You can read about it here. Downloads for all platforms can be found here.

Python tutor

Let’s meet Python on the web with Python Tutor is a great way to visualize Python code.

Use it as much as possible! . It really provides great guidance about how things are working under the hood.

By default works for standard Python code. If you want to use it also with code from modules (i.e. numpy) you have to select Write code in Python3 with Anaconda (experimental)

System console

Let’s look at the operating system console. In Anaconda installations you must open it with Anaconda Prompt (if you have a Mac but not Anaconda, open the Terminal). We assume Linux users can get around their way.

WARNING: In the system console we are entering commands for the operating system, using the system command language which varies for each operating system. So following commands are not Python !

  • to see files of the folder you are in you can type dir in windows and ls in Mac/Linux

  • to enter a folder: cd MYFOLDER

  • to leave a folder: cd ..

    • mind the space between cd and two dots

Python interpreter

To start the Python interpreter, from system console run (to open it see previous paragraph)

python

You will see the python interpreter (the one with >>>), where you can directly issue commands and see the output. If for some reason it doesn’t work, try running

python3

WARNING: you must be running Python 3, in this course we only use that version ! Please check you are indeed using version 3 by looking at the interpreter banner, it should read something similar to this:

Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

WARNING: if you take random code from the internet, be sure it is for Python 3

WARNING: the >>> is there just to tell you you are looking at python interpreter. It is not python code ! If you find written >>> in some code example , do not copy it !

Now we are all set to start interacting with the Python interpreter. First make sure you are inside the interpreter (you should see a >>> in the console, if not see previous paragraph), then type in the following instructions:

[2]:
5 + 3
[2]:
8

All as expected. The “In [1]” line is the input, while the “Out [1]” reports the output of the interpreter. Let’s challenge python with some other operations:

[3]:
12 / 5
[3]:
2.4
[4]:
1/133
[4]:
0.007518796992481203
[5]:
2**1000
[5]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

And some assignments:

[6]:
a = 10
b = 7
s = a + b
d = a / b

print("sum is:",s, " division is:",d)
sum is: 17  division is: 1.4285714285714286

In the first four lines, values have been assigned to variables through the = operator. In the last line, the print function is used to display the output. For the time being, we will skip all the details and just notice that the print function somehow managed to get text and variables in input and coherently merged them in an output text. Although quite useful in some occasions, the console is quite limited therefore you can close it for now. To exit type Ctrl-D or exit().

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.

[7]:
"""
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):

[8]:
"""
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 vaule 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.

[9]:
""" 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.

Jupyter

Jupyter is a handy program to write notebooks organized in cells (files with .ipynb extension), where there is both code, output of running that code and text. The code by default is Python, but can also be other languages like R). The text is formatted with Markdown language - see cheatsheet. It’s becoming the de-facto standard for writing technical documentation (you can find everywhere, i.e. blogs).

Run Jupyter

Jupyter is a web server, so when you run it, a Jupyter server starts and you should see a system console opening (on Anaconda system you might see it for a very short time), afterwards an internet browser should open. Since Jupyter is a server, what you see in the browser is just the UI which is connecting to the server.

If you have Anaconda :

Launch Anaconda Navigator, and then search and run Jupyter.`

If you don’t have Anaconda:

From system console try to run

jupyter notebook

or, as alternative if the previous doesn’t work:

python3 -m notebook

Editing notebooks

Useful shortcuts:

  • to execute Python code inside a Jupyter cell, press Control + Enter

  • to execute Python code inside a Jupyter cell AND select next cell, press Shift + Enter

  • to execute Python code inside a Jupyter cell AND a create a new cell aftwerwards, press Alt + Enter

Some tips:

  • when something seem wrong in computations, try to clean memory by running Kernel->Restart and Run all

  • when you see an asterisk to the side of a cell, maybe the computationg has hanged (an infinite while?). To solve the problem, run Kernel->shutdown and then `Kernel -> restart

Browsing notebooks

(Optional) To improve your browsing experience, you might wish to install some Jupyter extension , like toc2 which shows paragraphs headers on the sidebar. To install it:

Install the Jupyter contrib extensions package:

If you have Anaconda:

Open Anaconda Prompt, and type:

conda install -c conda-forge jupyter_contrib_nbextensions

If you don’t have Anaconda:

  1. Open a Terminal and type:

python3 -m pip install --user jupyter_contrib_nbextensions
  1. Install it in Jupyter:

jupyter contrib nbextension install --user
  1. Enable extensions

jupyter nbextension enable toc2/main

Once you installed: To see tocs when in a document you will need to press a list button at the right-end of the toolbar.

Course exercise formats

In this course, you will find the solutions to the exercises on the website. At the top page of each solution, you will find the link to download a zip like this:

Download exercises zip

Browse files online

  • now unzip exercises in a folder, you should get something like this:

-jupman.py
-sciprog.py
-other stuff ...
-exercises
     |- introduction
         |- introduction-exercise.ipynb
         |- introduction-solution.ipynb
         |- other stuff ..

WARNING 1: to correctly visualize the notebook, it MUST be in an unzipped folder !

Each zip contains both the exercises to do as files to edit, along with their solution in a separate file.

Some exercises will need to be done in Jupyter notebooks (.ipynb files), while others in plain .py Python files.

  • open Jupyter Notebook from that folder. Two things should open, first a console and then browser.

  • The browser should show a file list: navigate the list and open the notebook exercises/introduction/introduction-exercise.ipynb

WARNING 2: DO NOT use the Upload button in Jupyter, instead navigate in Jupyter browser to the unzipped folder !

  • now look into the exercise notebook, it should begin with a cell like this:

#Please execute this cell
import sys;
sys.path.append('../../');
import jupman;
import sciprog;

This is because some code is common to all exercises. In particular:

  • in jupman.py there is code for special cell outputs in Jupyter notebooks (like Python tutor or unit tests display)

  • in sciprog.py there are common algorithms and data structures used in the course

A notebook always looks for modules in the current directory of the notebook. Since jupman.py stays a parent directory in the zip, with the lines

import sys;
sys.path.append('../../');

we tell Python to also look modules (= python .py files) in a directory which is two parent folders above the current one.

It is not the most elegant way to locate modules but gets around the quirks of Jupyter fine enough for our purposes.

Shortcut keys:

  • to execute Python code inside a Jupyter cell, press Control + Enter

  • to execute Python code inside a Jupyter cell AND select next cell, press Shift + Enter

  • to execute Python code inside a Jupyter cell AND a create a new cell aftwerwards, press Alt + Enter

  • If the notebooks look stuck, try to select Kernel -> Restart

Python Tutor inside Jupyter

We implemented a command jupman.pytut() to show a Python tutor debugger in a Python notebook. Let’s see how it works.

You can put a call to jupman.pytut() at the end of a cell, and the cell code will magically appear in python tutor in the output (except the call to pytut() of course).

ATTENTION: To see Python tutor you need to be online!

For this to work you need to be online both when you execute the cell and when visiting the built website.

[10]:
x = 5
y= 7
z = x + y

jupman.pytut()
[10]:

Beware of variables which were initialized in previous cells which won’t be available in Python Tutor, like w in this case:

[11]:
w = 8
[12]:
x =  w + 5
jupman.pytut()
[12]:

Exercises

Try to familiarize yourself with Jupyter and Visual Studio Code by doing these exercises in both of them.

  1. Compute the area of a triangle having base 120 units (B) and height 33 (H). Assign the result to a variable named area and print it.

[13]:
# SOLUTION

B = 120
H = 33
Area = B*H/H
print("Triangle area is:", Area)
Triangle area is: 120.0
  1. Compute the area of a square having side (S) equal to 145 units. Assign the result to a variable named area and print it.

[14]:
S = 145
Area = S**2
print("Square area is:",Area)
Square area is: 21025
  1. Modify the program at point 2. to acquire the side S from the user at runtime. (Hint: use the input function and remember to convert the acquired value into an int).

ANSWER:

print("Insert size: ")
S = int(input())
Area = S**2
print("Square area is:",Area)
  1. If you have not done so already, put the two previous scripts in two separate files (e.g. triangle_area.py and square_area.py and execute them from the terminal).

  2. Write a small script (trapezoid.py) that computes the area of a trapezoid having major base (MB) equal to 30 units, minor base (mb) equal to 12 and height (H) equal to 17. Print the resulting area. Try executing the script from inside Visual Studio Code and from the terminal.

[15]:
# SOLUTION

"""trapezoid.py"""
MB = 30
mb = 12
H = 17
Area = (MB + mb)*H/2
print("Trapezoid area is: ", Area)
Trapezoid area is:  357.0
  1. Rewrite the example of the sum of the first 1200 integers by using the following equation: \(\sum\limits_{i=1}^n i = \frac{n (n+1)}{2}\).

[16]:
# SOLUTION

N = 1200

print("Sum of first 1200 integers: ", N*(N+1)/2)
Sum of first 1200 integers:  720600.0
  1. Modify the program at point 6. to make it acquire the number of integers to sum N from the user at runtime.

ANSWER:

print("Input number N:")
N = int(input())
print("Sum of first ", N, " integers: ", N*(N+1)/2)
  1. Write a small script to compute the length of the hypotenuse (c) of a right triangle having sides a=133 and b=72 units (see picture below). Hint: remember the Pythagorean theorem and use math.sqrt).

triangle 9u349y43

[17]:
# SOLUTION

import math

a = 133
b = 72

c = math.sqrt(a**2 + b**2)

print("Hypotenuse: ", c)
Hypotenuse:  151.23822268196622