MTH 337: Week 2

Lists

In [1]:
mylist = ['abc', 42, 3.14] # Create a list with surrounding square brackets
In [2]:
mylist
Out[2]:
['abc', 42, 3.14]
In [3]:
mylist = [] # Create an empty list
In [4]:
mylist
Out[4]:
[]
In [5]:
mylist.append('a') # "append" adds an item to the end of a list
print(mylist)
['a']
In [6]:
mylist.append('b')
print(mylist)
['a', 'b']
In [ ]:
a = 1
while a <= 5000:
    b = 1
    while b <= 5000:
        # test if (a, b) form PPT
        b += 1
    a += 1

"for" loops

In [7]:
for item in ['abc', 42, 3.14]: # "for" loops iterate over the items in some sequence
    print(item)
abc
42
3.14

"range" can be used to iterate over a sequence of integers

In [8]:
for i in range(5): # range(n) starts at zeo and ends at n - 1
    print(i)
0
1
2
3
4
In [9]:
for i in range(1, 5): # range(m, n) starts at m and ends at n - 1
    print(i)
1
2
3
4
In [ ]:
for a in range(1, 5001): # Something like this will be needed for Exercise 3 in Report 1
    # Blah
In [10]:
for i in range(2, 11, 2): # The third argument to range can be used to specify a step size between integers
    print(i)
2
4
6
8
10

Plotting with Matplotlib

In [1]:
%matplotlib inline # Generate graphs in notebook rather than separate window
In [2]:
import matplotlib.pyplot as plt # Standard way to import plotting functions

Create two lists and plot them:

  • $x = [x_1, x_2, \ldots, x_n]$ is a list of x-coordinates
  • $y = [y_1, y_2, \ldots, y_n]$ is a list of y-coordinates
  • $'r.'$ is a format string giving the color ($'r'$) and the marker type ($'.'$ for points)
  • $ms=20$ is a keyword argument specifying the marker size
In [3]:
x = [1,2,3,4,5,6,7,8,9,10]
y = [1,4,9,16,25,36,49,64,81,100]
plt.plot(x, y, 'r.', ms=20)
Out[3]:
[<matplotlib.lines.Line2D at 0x7f3620917be0>]

Plotting with square markers

In [4]:
x = [1,2,3,4,5,6,7,8,9,10]
y = [1,4,9,16,25,36,49,64,81,100]
plt.plot(x, y, 'rs', ms=20)
Out[4]:
[<matplotlib.lines.Line2D at 0x7f361b4bbf60>]

The default plot is 'b-' i.e. blue lines connecting points in the sequence

In [6]:
x = [1,2,3,4,5,6,7,8,9,10]
y = [1,4,9,16,25,36,49,64,81,100]
plt.plot(x, y) # No options given, so defaults are used
Out[6]:
[<matplotlib.lines.Line2D at 0x7f3620672828>]

Use the help system to explore what a function does and what the keyword options are.

In [5]:
? plt.plot

Labeling graphs

Add a title, x label and y label. These are all strings.

In [7]:
plt.plot([1,2,3,4,5], [1,4,9,16,25], 'ro')
plt.title("This is the title")
plt.xlabel('x')
plt.ylabel('y')
Out[7]:
<matplotlib.text.Text at 0x7f3620814710>
In [8]:
plt.plot([1,2,3,4,5], [1,4,9,16,25], 'ro')
plt.title("This is the title")
plt.xlabel('x')
plt.ylabel('y');

Change the figure size

Change the figure size to 8 units wide, 4 units high using plt.figure(figsize=(width, height)).

In [9]:
plt.figure(figsize=(8,4))
plt.plot([1,2,3,4,5], [1,4,9,16,25], 'ro')
plt.title("This is the title")
plt.xlabel('x')
plt.ylabel('y');
In [ ]: