Skip to main content

Section 2.4 Python recap

for loops. The for loop allows programmers to tell Python to repeat some set of instructions for a given number of times. The repeated instructions are all instructions that follow the for line and are indented.

Example 1: print the first 7 natural numbers (startin from 0!):

Example 2: print all natural numbers between 1 and 95 in increments of 19:

Arrays. When doing numerical computations, it is preferable to use NumPy's own arrays. There are several ways to accomplish this, two of which are shown in the example below. The instruction np.arange(k) generates an array (i.e. a vector, in more mathematical terms) of \(k\) elements, the first of which is 0 (so that the component of index \(k\) is equal to \(k-1\)). The instruction np.zeros(k) generates an array of \(k\) elements, each of which equal to zero. With a notation similar to MATLAB, it is possible to access a range of elements of an array x between indices \(i\) and \(j\) with the code x[i:j+1] (see the example below).

Below are examples to generate arrays of equally spaced points, which can be useful in many cases.

Remark: the syntax x=np.linspace(a,b,n) is equivalent to x=np.arange(a,b,(b-a)/(n-1)); usually when the emphasis is on the number of array elements between a and b one uses the first while when the emphasis is on the spacing between tweo consecutive elements of the array one uses the latter.

Operations with vectors. NumPy's vectors (unlike Python's standard arrays!) behave very similarly to MATLAB's ones: 1. if x and y are vectors of the same dimension, they can be summed/subtracted/multiplied/divided by each other and by scalars (be careful with divisions, you cannot divide by zero!); 2. NumPy's functions act on vectors by evaluating the function componentwise.
Plots The standard Python visualization module is MatPlotLib. In order to load this module, usually we write from matplotlib import pyplot as plt. Most of the times, you will need to plot an array b versus an array a. This is done via the plot command as in the example below:

If you do not want Python to draw the lines connecting consecutive points, you need to use the scatter command:

When plotting the graph of an exponential nature, it is often more useful to plot the log of the "y" with respect to the log of the "x", which is accomplished by the loglog function, whose syntax is the same of the plot one.

What is the slope of the line above?

Plot title and labels. It is a good idea to always include a title and labels to any plot you do. Below is an example of how to accomplish that. Notice that the title below contains TeX code for Math typing. it is not needed to put the r before the first " symbol if you do not need to type any Math formula.