import numpy as np
import matplotlib.pyplot as plt
import math as m
from mpmath import mp, iv
Evaluate m.cos?
to find out
about the m.cos
function.
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.")
# Creation
lst = [1, 4, 5]
# Length
len(lst)
# Access
lst[0]
# Assembly
lst2 = []
for x in lst:
lst2.append(x**2)
# For loop over list
for x in lst:
print(x)
# while loop
while n < 100:
print(n)
n += 1
list(range(5))
list(range(2, 7))
list(range(1, 11, 2))
s = "0123456789"
## Character access
s[7]
# Length
len(s)
# Substring
s[start:end]
# Formatting
"There are {} dogs.".format(n)
# convert int to string
str(53)
# convert string to int
int('53')
def f(x):
return x**2 + x - 3
# 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)
# 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()
Assert statements are used to raise errors if something is not True.
# 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'
# 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))
try:
x = 5 / (3 - 3)
except ZeroDivisionError:
# Deal with the error
print('You divided by zero!')