Programming Concepts

Standard imports

In [ ]:
import numpy as np
import matplotlib.pyplot as plt
import math as m
from mpmath import mp, iv

Built in help

Evaluate m.cos? to find out about the m.cos function.

Branching

In [ ]:
if n % 3 == 0:
    print("n is a multiple of 3.")
elif n % 3 == 1:
    print("n-1 is a multiple of 3.")
else:
    print("n-2 is a multiple of 3.")

Lists

In [ ]:
# Creation
lst = [1, 4, 5]
# Length
len(lst)
# Access
lst[0]
# Assembly
lst2 = []
for x in lst:
    lst2.append(x**2)

Looping

In [ ]:
# For loop over list
for x in lst:
    print(x)
# while loop
while n < 100:
    print(n)
    n += 1

Ranges

In [ ]:
list(range(5))
In [ ]:
list(range(2, 7))
In [ ]:
list(range(1, 11, 2))

Strings

In [ ]:
s = "0123456789"
## Character access
s[7]
# Length
len(s)
# Substring
s[start:end]
# Formatting
"There are {} dogs.".format(n)

Strings and Ints

In [ ]:
# convert int to string
str(53)
# convert string to int
int('53')

Functions

In [ ]:
def f(x):
    return x**2 + x - 3

Interval Arithmetic

In [ ]:
# Set bits of precision
iv.prec = 53
# Set digits of precision
iv.dps = 17
# Constructing 2/5
iv.mpf(2)/iv.mpf(5)
iv.mpf("2/5")
# pi:
iv.pi
# Basic functions
iv.sin(x)
iv.cos(iv.pi/iv.mpf(3))
# Width of an interval x
x.delta
# Printing 5 significant digits
iv.nstr(x, 5)

Plotting with matplotlib

In [ ]:
# Distribution of values in [a,b]
x = np.linspace(a, b, 1001)
# if f() accepts Numpy arrays
y = f(x)
# if f() accepts only floats
y = np.array([f(xx) for xx in x])
# Draw the graph y = f(x):
plt.plot(x, y)
# Draw a second graph
plt.plot(x2, y2)
# Show it:
plt.show()

Assertions

Assert statements are used to raise errors if something is not True.

In [ ]:
# Does nothing:
assert True, 'Error text'
# Raises an error:
assert False, 'Error text'
# Raises an error if n is negative
assert n>=0, 'n should be nonnegative'

Error handling

In [ ]:
# Dealing with assertion errors.
try:
    # Some code including function calls that might lead to an AssertionError
except AssertionError as e:
    # Deal with the error
    # You can print out the details of the error with:
    print(repr(e))
In [ ]:
try:
    x = 5 / (3 - 3)
except ZeroDivisionError:
    # Deal with the error
    print('You divided by zero!')