Introduction to Python Practical 1 Daniel Carrera & Brian Thorsbro October 2017 1 Introduction I believe that the best way to learn programming is hands on, and I tried to design this practical that way. No prior knowledge of Python is assumed, but you must already have it installed. By installing the anaconda package that can be downloaded for free python will be installed as well. Please install version 3.6 (or newer). Different tools are installed by anaconda, and the Spyder tool is what I find the most useful for small python scripts. Installation website: https://www.anaconda.com/download/ 2 Whirlwind tour of Python 2.1 Python as a calculator Locate the Spyder program and run it. After the program starts, you will be presented with a command shell, default in the bottom right corner, where you enter python instructions. In the rest of this tutorial, any line that starts with >> denotes the python command shell, which normally looks a bit like In [nnn]:. For example: >> 2 + 3 5 At the simplest level you can use python as a scientific calculator. Enter the following code and see what it does. 1
>> 2 * 5 >> 2 + 3 * 5 + 1/2 >> 3**2 >> 3**3 >> 3**4 >> 4**(-1) >> 4**(1/2) You can enter arithmetic operations directly into the command window. The symbol ** denotes exponentiation (so you write 5 17 as 5**17). For mathematical functions and constants you need to load the math library, as shown in the first line in the following. >> sqrt(2) >> sqrt(4) >> sqrt(25) >> pi >> cos(pi) >> sin(pi/2) >> tan(pi/4) >> arctan(1) >> arctan(tan(0)) Note, that you can also use import numpy instead of from math import *, but then you would have to preamble all your expressions with numpy., for example numpy.sqrt(2). Some programmers considers this to be more clean code, as it shows the library usage explicitly. Also know that a math library also exists for importing the mathematical functions, but the numpy library also supplies these mathematical functions with more functionality for advanced data structures. >> exp(0) >> exp(1) >> exp(2) 2
>> e >> log(e) >> log(10) >> log(e**173) >> log(exp(173)) >> log10(e) >> log10(10) >> log10(1000) >> log10(10**189) The function exp(x) returns e x where e = 2.7183... is the base of the natural logarithm. The function log() gives the natural logarithm while log10() gives the logarithm base 10. >> 1j >> 5j >> 2 + 1j >> (-1)**0.5 >> exp(1j*pi) >> log(1j) >> sin(1j) >> sinh(1j) The syntax 3j, 5j, etc lets you write imaginary numbers safely. You must write 1j, writing just j is not sufficient. >> from math import * >> help(log10) Python has an extensive help system. Unfortunately this does not help so much with numpy library, using google is recommended. 3
2.2 Vectors and linear algebra >> u = array([1.0,2.0,3.0]) >> v = array([3.0,4.0,12.0]) >> u + v >> u - v >> u * v >> u / v >> v ** u >> 3 * u >> 3 * u - v >> dot(u,v) >> dot(v,v) >> sqrt( dot(v,v) ) >> linalg.norm(v) One way to create a vector is to enter the vector components directly inside square brackets. In this example you created row vectors u = [1, 2, 3] and v = [3, 4, 12]. You can do vector addition, subtraction, multiplication, division, exponential, scalar multiplication and dot product. Using an operator between two arrays causes the operator to be applied element by element through the arrays (which have to be of equal length). Note that these are not matrix operations. The function linalg.norm returns the norm, or the magnitude of a vector. >> u = mat([1.0,2.0,3.0]) >> v = mat([3.0,4.0,12.0]) >> u >> v >> transpose(u) >> transpose(v) >> transpose(u) * v >> u * transpose(v) The vectors u and v are in this example matrices of one dimension, and not arrays. Those the operators between them become matrix operations and for two row vectors you need to take the transpose of one of the vectors to multiply them. 4
>> v = mat([3.0,4.0,12.0]) >> w = mat([[1.0],[2.0],[3.0]]) >> w * v >> v * w You can enter a column vector directly if you double square brackets to type in the data row by row. 2.3 Conditionals >> a = 1 >> b = 2 >> if a == b: x = 2 elif a >= 3: x = 7 else: x = 0 >> x In python indentation is very important, it marks the structure. For the elif, which means else if, it has to be at the same indentation as the first if statement it belongs to. Experiment with different values of a and b and different conditions (e.g. == <= => < >). What happens if a and b are arrays? Try the following examples: >> a = array([1,2,3]) >> b = array([1,2,3]) >> a == b >> b = array([1,2,4]) >> a == b >> if any(a == b): 5
x = 2 else: x = 0 >> x >> if all(a == b): x = 2 else x = 0 >> x Experiment with different arrays (e.g. b = [3 1 2]). What do the functions any and all do? >> arange(3,11) >> arange(3,11,2) >> arange(2.5,7.5) >> arange(2.5,7.5,2) >> arange(2,7,1.5) The function arange offers different ways of constructing arrays running through a series of numbers, the third argument is the step size. >> from matplotlib.pyplot import * >> x = arange(1,10) >> y = x ** 2 >> plot(x, y) >> plot(x, cos(x)) By this point you have learnt enough python to produce many useful plots. Use x = arange(a,b,q) to create a series of X values, and use vector or array operations to produce the corresponding Y values. The plot command is very flexible and can produce a lot of nice plots. 6
Enter the following code and see what it does. Use the Up arrow key to pull up previous lines so that you can save typing: >> from matplotlib.pyplot import * >> x = arange(0,2*pi,0.1) >> y = sin(x) >> plot(x,y, r ) >> plot(x,y, g ) >> plot(x,y, b ) >> plot(x,y, m ) >> plot(x,y, y ) >> plot(x,y, k ) >> plot(x,y, c ) >> plot(x,y, r- ) >> plot(x,y, ro ) >> plot(x,y, r+ ) >> plot(x,y, r* ) >> plot(x,y, rx ) >> plot(x,y, r^ ) >> plot(x,y, ro- ) >> plot(x,y, r+- ) >> plot(x,y, go- ) >> y2 = cos(x) >> plot(x,y, r,x,y2, b );legend([ Sine, Cosine ]);title( Sines and Cosines ) >> plot(x,y, r );plot(x,y2, b );xlabel( This is the X axis ) The plot function accepts an optional formatting string to define the colour, plot style and data label. You can include any number of data sets in the same plot. In this example the semicolon is used to separate commands, because the plot is reset when hitting enter. When you later make programs you can type the commands on a line each instead of using semicolon, i.e. like shown in this code snippet. from numpy import * from matplotlib.pyplot import * figure() x = arange(0,2*pi,0.1) y = sin(x) 7
y2 = cos(x) plot(x,y, r ) plot(x,y2, b ) legend([ Sine, Cosine ]) title( Sines and Cosines ) xlabel( This is the X axis ) ylabel( This is the Y axis ) Notice the usage of figure() which sets up a new clean plot. 2.4 Making python programs Click on the New File button to open the built-in python editor in Spyder. You can use the editor to write python programs. Python programs contain a sequence of python commands, allowing you to store complex operations for later use. When you save the program, the file name should have the extension.py. Enter this in the editor: """ wave.py -- An simple animation of a travelling wave. """ from numpy import * for idx in arange(1,4): print(idx) Save this file as wave.py in the current working directory. After the file is saved, Enter the following in the command window and see what it does; >> run wave.py This program should print the integers from 1 to 3. This program only contains a short for loop. A for loop allows you to repeat commands a fixed number of times as the index variable (in this case idx) steps through the values of an array. You can also run the program by hitting the green play button in the Spyder interface. 8
Replace the for loop with the one below and run the program again to see what it does: for idx in arange(1.5,3.5,0.5): print(idx) # print the idx print(idx * idx) # print the idx squared The index variable in a for loop can step through the values of any array. The program also shows comments. A comment goes from the # sign to the end of the line. Always comment your programs generously and clearly. A block comment going over several lines can be started with the """ sequence and the program ignores everything until the sequence is found again. It is a good way to exclude some code from a program without deleting it, should you want to save it. 3 Exercises It is important that you do the exercises, as they will help sharpen your skills with loops, plotting and finding help on python functions. The last problem is mainly to help you play with python. Exercise 1: The Fibonacci sequence is a series of integers, starting with 1,1, where the next value is the sum of the previous two values. The first few terms of the Fibonacci sequence are: 1,1,2,3,5,8,13,... Write a program that prints the first 50 values of the Fibonacci sequence. Exercise 2: Try to make a plot similar to the one on the next page. The plot compares the values produced by the norm function with the Gaussian distribution (in particular norm.ppf, norm.pdf, and norm.rvs). You will find the the norm functions in the scipy.stats library. Try to find help on these functions on the internet and then use the plot functions from matplotlib.pyplot to produce your plot, in particular you might find the plotting function hist useful for part of this exercise. Exercise 3: Type in the following code in a program, save it, and run it to see what it does: from mpl_toolkits.mplot3d import Axes3D from matplotlib.pyplot import * from numpy import * # Setting up the grid that is worked upon X = arange(-8, 8, 0.5) Y = arange(-8, 8, 0.5) X, Y = meshgrid(x, Y) 9
# defining the Z axis value, try make other functions! R = sqrt(x**2 + Y**2) Z = sin(r) / R # do the actual 3D plotting fig = figure() ax = fig.gca(projection= 3d ) surf = ax.plot_surface(x, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=false) ax.set_zlim(-1.01, 1.01) ax.zaxis.set_major_locator(linearlocator(10)) ax.zaxis.set_major_formatter(formatstrformatter( %.02f )) fig.colorbar(surf, shrink=0.5, aspect=5) Advanced 3D plotting techniques exists in python. shape (a bowl, a volcano, a sombrero, etc). Try to make a plot with an interesting 10