# Theory 0 ## MSc Python Crash Course: Basic Operations in the Python Console MSc MATLAB Crah Course Originally written by Nick Hale, Oct. 2013. Extended by Asgeir Birkisson, Oct. 2014, 2015. Modified by Behnam Hashemi and Hadrien Montanelli, Sep. 2016. Python Crash Course by Benjamin Walker, Oct. 2025. ## Getting Set Up Everyone should be on the command line, with anaconda installed and activated. If installed correctly, you should have `(base)` at the start of your command line. If not, please talk to one of the teachers who can help you. Python consists of packages, and anaconda is the package manager we will use during this crash course. Anaconda uses environments, which are isolated spaces where you can install a specific collection of packages for a project, without affecting other projects. It is best practice to create a new, separate environment for each project you work on. This prevents versioning conflicts and makes your work more easily reproducible. Currently, you are in the base environment, which comes with a large number of packages pre-installed. While convenient for quick testing, you should not install new packages in the base environment, or use it for any serious projects. Therefore, let's begin by creating a new python environment, with the name `Intro2Py'. $ conda create -n Intro2Py python=3.12 Now we have created the environment we activate it. $ conda activate Intro2Py Once in an environment, you can get out of it by deactivating. $ conda deactivate $ conda activate Intro2Py For theory 0, we will only need two packages, numpy for handling vectors and matrices and matplotlib for plotting. When in the desired environment, these can be installed as follows. $ conda install numpy matplotlib ## Simple Introduction With these packages installed, we can now move into the python console. $ python Here, we can execute individual lines of python code. >>> 5 + 10 >>> 3 - 2 >>> 3 * 2 >>> 3 / 2 >>> 3 ** 2 >>> (1 + 2j) * (2 + 4j) >>> exp(3) `NameError: name 'exp' is not defined' We now need our first package, the `math' package, which is part of The Python Standard Library, a set of packages that come with any python installation. >>> import math Functions within python packages are exposed to the user via the dot notation. >>> math.exp(3) >>> math.sqrt(9) >>> math.factorial(5) >>> math.sin(3) >>> math.sin(math.pi) >>> math.sin(math.radians(90)) You can also get help with the available functions in a package. >>> help(math) One thing you may have noticed is we have to type out the package name multiple times. To speed things up we can import functions directly from packages. >>> from math import sin, pi >>> sin(pi) Or we can import packages with an alias. >>> import math as m >>> m.exp(3) ## List and Tuples Now, we want to start working with collections of data, e.g. vectors. There are two options native to python, a tuple or a list. >>> tupl = (1, 2, 3) >>> lis = [1, 2, 3] >>> help(tupl) >>> help(lis) As help told us, a tuple is an immutable sequence, whereas a list is a mutable sequence. >>> lis[0] = 4 >>> lis >>> tupl[0] = 4 `TypeError: 'tuple' object does not support item assignment' Let's try using a list as a vector. >>> vec1 = [1, 2, 3] >>> vec2 = [4, 5, 6] >>> vec1 + vec2 >>> vec1 * vec2 `TypeError: can't multiply sequence by non-int of type 'list'' Not quite what we were looking for! We could try using list comprehensions. >>> [a + b for a,b in zip(vec1, vec2)] But we are better off using a package which has been designed with vectors in mind, numpy. ## Numpy >>> import numpy as np >>> vec1 = np.array([1, 2, 3]) >>> help(vec1) >>> vec1.shape >>> vec2 = np.array([4, 5, 6]) >>> vec1 + vec2 >>> vec1 * vec2 >>> np.transpose(vec1) Maybe not what we were expecting for the transpose of a vector. However, vec1 is a 1-dimensional vector right now. >>> vec1 = np.array([[1, 2, 3]]) >>> vec1.shape >>> np.transpose(vec1) Let's revert back to a 1-dimensional vector. >>> vec1 = np.array([1, 2, 3]) >>> vec1.max() >>> vec1.min() >>> vec1.sum() >>> vec1.mean() >>> 4 * vec1 >>> vec3 = 3*vec1 + 5*vec2 >>> vec3 We can modify the values in a numpy array. >>> vec3[1] = 5; vec3 The semi-colon denotes the end of a line, which we will use to immediately see the impact of our code on `vec3'. >>> np.append(vec3, [2, 1]); vec3 >>> vec3 = np.append([1, 2], vec3); vec3 >>> vec3 = np.delete(vec3, [1, 3]); vec3 There are multiple methods for initialising an array without typing all the values out. >>> np.arange(1, 100) >>> np.arange(1, 100, 10) >>> np.arange(20, -5, -1.5) >>> np.linspace(0, 1, 51) You can access specific values of an array using indexing and slicing. >>> x = np.arange(1, 101) >>> x[49] >>> x[49:60] >>> x[49:60:2] # start:stop:step >>> x[:88:-1] We can also work with matrices using numpy. >>> mat1 = np.array([[1, 2], [3, 4]]); mat1 >>> np.transpose(mat1) >>> mat1.shape >>> mat1.max() >>> mat1.max(axis=0) >>> mat1.max(axis=1) >>> mat1.sum(axis=1) >>> mat1.mean(axis=0) >>> mat2 = np.array([[5, 6], [7, 8]]) >>> mat3 = 3*mat1 + mat2; mat3 >>> mat3[1, 0] >>> mat3[:, 0] >>> mat3[1, :] >>> np.diag(mat3) >>> np.zeros([3, 3]) >>> np.ones([3, 3]) >>> np.eye(3) ## Linear Algebra Sometimes, the functions you need will be in subpackages, such as `np.random' or `np.linalg', which we will import using aliases. >>> import numpy.linalg as npla >>> import numpy.random as npr >>> mat4 = npr.rand(3, 3); mat4 >>> npla.det(mat4) >>> npla.eig(mat4) >>> eval, evec = npla.eig(mat4) >>> Q, R = npla.qr(mat4) >>> Q * np.transpose(np.conjugate(Q)) The `*' operator performs entry-wise multiplication. Need to use the `@' symbol for matrix multiplication. >>> Q @ np.transpose(np.conjugate(Q)) >>> mat4 - Q @ R Can also solve linear systems. >>> A = np.array([[1, 2], [5, 8]]) >>> b = np.array([[1], [2]]) >>> x = npla.solve(A, b); x >>> x = npla.inv(A) @ b; x This second approach isn't recommended, it isn't efficient and can lead to numerical instabilities. ## Dictionaries A dictionary is a collection of key–value pairs. Each key is unique, and is used to access its corresponding value. >>> student = {'name': 'Alice', 'age': 24} >>> student['name'] >>> student['age'] We can add, modify, and delete entries. >>> student['course'] = 'Maths' >>> student['age'] = 25 >>> del student['name'] >>> student We can also view the available keys and values. >>> student.keys() >>> student.values() ## Plotting Let's finish with some plotting. >>> import matplotlib.pyplot as plt >>> x = np.linspace(-1, 1, 100) >>> plt.plot(x, np.sin(4 * math.pi * x)) >>> plt.show() >>> plt.plot(x, np.sin(4 * math.pi * x)) >>> plt.plot(x, np.exp(np.cos(10 * x))) >>> plt.show() And now we can exit our python console. >>> exit()