Basics of Python language¶

Variables and type¶

Symbol names¶

There are a number of Python keywords that cannot be used as variable names. These keywords are: and, as, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, with, yield

Note: Be aware of the keyword lambda, which could easily be a natural variable name in a scientific program. But being a keyword, it cannot be used as a variable name.

Fundamental types / lists / touples¶

In [1]:
x=1
print (type(x))
x=1.0
print (type(x))
x=True
print (type(x))
x=1.0+1.j
print (type(x))
x = 'my string'

print (type(x), len(x))
x = [1,2,3.0,2.+3j]
y = (1,2,3.0,2.+3j)
print(type(x))
print(type(y))

x[2]='ss'
print([type(i) for i in x], [type(i) for i in y])
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'complex'>
<class 'str'> 9
<class 'list'>
<class 'tuple'>
[<class 'int'>, <class 'int'>, <class 'str'>, <class 'complex'>] [<class 'int'>, <class 'int'>, <class 'float'>, <class 'complex'>]
In [2]:
## equivalent statements
print([type(i) for i in x])
## equivalent statements
r=[]
for i in x:
    r.append(type(i))
print(r)

## creates tuple or generator
r=(type(i) for i in x)
print(r)
for i in r:
    print(i)
[<class 'int'>, <class 'int'>, <class 'str'>, <class 'complex'>]
[<class 'int'>, <class 'int'>, <class 'str'>, <class 'complex'>]
<generator object <genexpr> at 0x1061a2c00>
<class 'int'>
<class 'int'>
<class 'str'>
<class 'complex'>

Formating strings and print statement¶

In [3]:
help(print)
Help on built-in function print in module builtins:

print(*args, sep=' ', end='\n', file=None, flush=False)
    Prints the values to a stream, or to sys.stdout by default.
    
    sep
      string inserted between values, default a space.
    end
      string appended after the last value, default a newline.
    file
      a file-like object (stream); defaults to the current sys.stdout.
    flush
      whether to forcibly flush the stream.

In [4]:
print('a','b', sep=', ',end='\n\n')
a, b

In [5]:
from math import *
print('This is old '+'type', pi, 1)
print('This just prints a string')
This is old type 3.141592653589793 1
This just prints a string

String Modulo Operator %:

%[flags][width][.precision]type

type:

  • d, i, u : integer
  • f, F : floating point
  • e, E : floating point with e notation
  • g, G : floating point or e notation
  • s, r, a : string
  • x, X : hexadecimal integer
  • o : octal integer
In [6]:
"just two numbers %s %s" % ('33','12')
Out[6]:
'just two numbers 33 12'
In [7]:
'This is formating for %s which has value %-10.4f and integer part %3d' % ('pi',pi,pi)
Out[7]:
'This is formating for pi which has value 3.1416     and integer part   3'
In [8]:
print('%o' % 16)
print('%x' % 16)
print(bin(16))
20
10
0b10000
In [9]:
# formatting string
print('This is old %10s  %12.10f  %5d' % ('type',pi, pi))
This is old       type  3.1415926536      3
In [10]:
print(1.0, 'str1', 'str2', 'str3'+'str4', end='\n')
print('sstr')
1.0 str1 str2 str3str4
sstr

Python2 type of printing, still very useful**¶

In [11]:
from math import *
print( 'value of pi is %20.5f and integer part %d' % (pi, pi) )
value of pi is              3.14159 and integer part 3
In [12]:
print( 'value of pi is %20.5s and integer part %d' % (pi, pi) )
value of pi is                3.141 and integer part 3
In [13]:
str(pi)
Out[13]:
'3.141592653589793'

More Python3 oriented printing**¶

In [14]:
print('value of pi is {} and integer part {}'.format(pi, int(pi)))
value of pi is 3.141592653589793 and integer part 3
In [15]:
print('value of pi is {0:6.4f} and integer part {1:d}'.format(pi, int(pi)))
value of pi is 3.1416 and integer part 3
In [16]:
print('value of pi is {1:6.4f} and integer part {0:d}'.format(int(pi),pi))
value of pi is 3.1416 and integer part 3
In [17]:
print(r'{}  {}'.format(3,5))
3  5

We can also skip default values, like position argument or types

In [18]:
print('value of pi is {:6.4f} and integer part {:}'.format(pi,int(pi)))
value of pi is 3.1416 and integer part 3
In [19]:
print('value of pi is {:} and integer part {:}'.format(pi,int(pi)))
value of pi is 3.141592653589793 and integer part 3

format type notation:

  • d : integer
  • f, F : floating point
  • e, E : floating point with e notation
  • g, G : floating point or e notation
  • s, r : string
  • x, X : hexadecimal integer
  • o : octal integer
  • b : binary

F-strings, the third way to print¶

F-strings were first introduced in Python 3.6. They are formatted string literals, i.e., f-strings are string literals that have an f before the opening quotation mark. They can include Python expressions enclosed in curly braces. Python will replace those expressions with their resulting values. So, this behavior turns f-strings into a string interpolation tool.

In [20]:
name,age='Jane',25

f"Hello, {name}! You're {age} years old."
Out[20]:
"Hello, Jane! You're 25 years old."

You can embed almost any Python expression in an f-string. This allows you to do some nifty things, for example:

In [21]:
print(f"Hello, {name.upper()}! You're {age} years old.")

f"{[2**n for n in range(3, 9)]}"
Hello, JANE! You're 25 years old.
Out[21]:
'[8, 16, 32, 64, 128, 256]'

Adding formatting to the string is possible. We use the same specifiers as used in ''.format() function, but the embedded expression comes before the format specifier, which always starts with a colon. This syntax makes the string literals readable and concise.

In [22]:
f"Value of pi is {pi:.4f}"
Out[22]:
'Value of pi is 3.1416'

Using more interesting formating

  • * is the fill character. It means that the string will be padded with = characters if the value is shorter than the specified width.
  • ^ indicates center alignment. It will align the string to the center within the specified width.
In [23]:
heading = "Centered string"
f"{heading:*^50}"
Out[23]:
'*****************Centered string******************'

Lists¶

The syntax for creating list is [..,..,]

The index starts with 0, like in C (not like in Fortran). Negative indices allowed.

List can contain different types, and can be nested

Slicing works just as with strings or arrays. Notation [start:end:step], defaults can be omitted

In [24]:
l1=[1,'a',1.0,-1.1]
print(l1[0], l1[-1])
l2=[1,[1,[2,3]]]        # nested list
print(l1[1::2] )        # start with 1st, and take every second till the end
print(list(range(10)))  # range used in loops
print(list(range(1,10,2))) # similar sintax: start,end,step
1 -1.1
['a', -1.1]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
In [25]:
w=range(1,20,2)
v=list(w)
print(w)
print(v)
range(1, 20, 2)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
In [26]:
v[1:-1:2]
Out[26]:
[3, 7, 11, 15]

Modifying a list:

  • append
  • insert
  • remove
  • del
In [27]:
l=['pre','filled'] # empty list
l.append('A')  # add at the end
l.append('d')
l.append('f')
print(l)
l[1]='e'       # modify
print(l)
l.insert(1,'k') # insert at specific location to extent the list
print(l)
l.remove('f')   # remove specific element, which must exist
print(l)
del l[1]        # remove an element at specific location
print(l)
['pre', 'filled', 'A', 'd', 'f']
['pre', 'e', 'A', 'd', 'f']
['pre', 'k', 'e', 'A', 'd', 'f']
['pre', 'k', 'e', 'A', 'd']
['pre', 'e', 'A', 'd']

How to properly use del:

In [28]:
# delete from back not front

l=list(range(20))
print('Start with:', l)
to_delete = [5,6,10]
for i in to_delete:
    del l[i]
print('After  del:', l)


l=list(range(20))
to_delete=sorted(to_delete)
print(to_delete[::-1])

for i in to_delete[::-1]:
    del l[i]
print('After proper del:', l)
Start with: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
After  del: [0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19]
[10, 6, 5]
After proper del: [0, 1, 2, 3, 4, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19]

Usefulnes of keyword in:

In [29]:
# Use of keyword 'in'

a=[3,4,7,8,9,10]

if 20 in a:
    a.remove(20)
    
print(3 in a)

if 10 in a:
    print(a)
True
[3, 4, 7, 8, 9, 10]

Tuples¶

Tuples are similar to lists, but they are not-modifiable.

Their most important use is in returning from a function, and in print statement, and as keys to dictionary.

In [30]:
point=(10,20,30)
#point[2]=2
print(point[2])
# point[0]=1 # can not be done
point=(1,20,30) # modifying the entire tuple is allowed, i.e., it is not a constant
#unpack it
x,y,z = point
print(x,y)

def Simple():
    # need to return several things
    return ('a','b','c')

x,y,z = Simple()
print(x,y,z)
30
1 20
a b c

Dictionaries¶

Dictionaries are like lists, but their keys are not integers, rather key can be any scalar type or tuple of scalar types

Dictionary is constructed by {...}

In [31]:
# This acts just like list
di={}
di[0]='a'
di[1]='b'
di[2]='c'
print(di) 
print(di[0], di[1], di[2])

# Generic keys, any immutable type (including tuples)
dj={}
dj[300]='c'
dj[600]='d'
dj['cde']=1
dj[(1,2)]=5
print(dj)

print(dj[(1,2)])

## Python2 : if dj.has_key((3,4)): 
if (3,4) in dj:
    print(dj[(3,4)])
else:
    dj[(3,4)]='something'

print(dj)
print()


# can also construct all at once
dk={300:'c', 600:'d', 'cde':1, (1,2):5}


# print it out by iterating over keys
for k in dk.keys():
    print('p1['+str(k)+']=', dk[k])
print()    

# but in Python3 you can equivalently write
for k in dk:
    print('p2['+str(k)+']=', dk[k])
print()
# print by iterating over (key,value) pairs
for k,v in dk.items():
    print('p3['+str(k)+']=',v)
{0: 'a', 1: 'b', 2: 'c'}
a b c
{300: 'c', 600: 'd', 'cde': 1, (1, 2): 5}
5
{300: 'c', 600: 'd', 'cde': 1, (1, 2): 5, (3, 4): 'something'}

p1[300]= c
p1[600]= d
p1[cde]= 1
p1[(1, 2)]= 5

p2[300]= c
p2[600]= d
p2[cde]= 1
p2[(1, 2)]= 5

p3[300]= c
p3[600]= d
p3[cde]= 1
p3[(1, 2)]= 5
In [32]:
list(dk.keys())
Out[32]:
[300, 600, 'cde', (1, 2)]
In [33]:
list(dk.items())
Out[33]:
[(300, 'c'), (600, 'd'), ('cde', 1), ((1, 2), 5)]
In [34]:
list(dk.values())
Out[34]:
['c', 'd', 1, 5]

Useful application of dictionary for storing sparse matrix or index arrays

In [35]:
from math import *

# sparse matrix:

di={(100,100):pi,(100,300):2*pi}
print(di)

# index to list
# consider a list
r = [10,100,30,5]


# we want an index array, that when given key=100 gives position in the list=1
d={}
for i in range(len(r)):
    d[r[i]]=i
print('index-d=', d)

#equivalent but nicer
for i,v in enumerate(r):
    d[v]=i
print('index-d=', d)

# The opposite operation is simple enumerate:
list(enumerate(r))
{(100, 100): 3.141592653589793, (100, 300): 6.283185307179586}
index-d= {10: 0, 100: 1, 30: 2, 5: 3}
index-d= {10: 0, 100: 1, 30: 2, 5: 3}
Out[35]:
[(0, 10), (1, 100), (2, 30), (3, 5)]

Control flow¶

We want to understand the following commands:

  • if, else, elif

  • loops using for & while

  • List comprehensions: inline for statement

    [< do something with i >for i in data]

In [36]:
statement1=statement2=statement3=True
statement2=False

if (statement1):
    if (statement2):
        print ('both statements are true')
    elif (statement3): # like else if
        print ('statement2 is wrong but statement3 is true')
    else:
        print('statement2=False and statement3=False')
statement2 is wrong but statement3 is true
In [37]:
[bool(100), bool(0), bool(''), bool([]), bool(['a'])]
Out[37]:
[True, False, False, False, True]
In [38]:
# scalar versus non-scalar values. 
# How is python handling scalars and non-scalars?

# scalar behaviour in python
a=b=g=3
g=4
print('a=',a,'b=',b,'g=',g)
b=1
print('a=',a,'b=',b,'g=',g)



# non scalar
a=b=g=[3]  # this statement
g[0]=4

print('a=',a,'b=',b, 'g=', g)

b=[1]  # this statement decoupled b from a and g
print('a=', a, 'b=', b, 'g=',g)
a= 3 b= 3 g= 4
a= 3 b= 1 g= 4
a= [4] b= [4] g= [4]
a= [4] b= [1] g= [4]
In [39]:
for x in range(-3,3,1):
    print(x)
    
ls=['scientific','computing','in','Python']
for word in ls:
    print(word)
    
for i,word in enumerate(ls):
    print('At index',i, 'we have string',word)
    
for i in range(len(ls)):
    word = ls[i]
    print('At index',i, 'we have string',word)       
-3
-2
-1
0
1
2
scientific
computing
in
Python
At index 0 we have string scientific
At index 1 we have string computing
At index 2 we have string in
At index 3 we have string Python
At index 0 we have string scientific
At index 1 we have string computing
At index 2 we have string in
At index 3 we have string Python
In [40]:
i=0
while i<5:
    print(i)
    i+=1
0
1
2
3
4
In [41]:
for i in range(10000):
    if i>=5: break
    print(i)
0
1
2
3
4
In [42]:
i=0
while True:
    if i>=5: break
    print(i)
    i+=1
0
1
2
3
4
In [43]:
l1=[]
for x in range(5):
    l1.append(x**2)
print(l1)
[0, 1, 4, 9, 16]
In [44]:
l1=[x**2 for x in range(5)]
print(l1)
[0, 1, 4, 9, 16]
In [45]:
[(j,i) for j in range(5) for i in range(5)]
Out[45]:
[(0, 0),
 (0, 1),
 (0, 2),
 (0, 3),
 (0, 4),
 (1, 0),
 (1, 1),
 (1, 2),
 (1, 3),
 (1, 4),
 (2, 0),
 (2, 1),
 (2, 2),
 (2, 3),
 (2, 4),
 (3, 0),
 (3, 1),
 (3, 2),
 (3, 3),
 (3, 4),
 (4, 0),
 (4, 1),
 (4, 2),
 (4, 3),
 (4, 4)]
In [46]:
for i in range(5):
    for j in range(5):
        print (i,j)
0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
2 4
3 0
3 1
3 2
3 3
3 4
4 0
4 1
4 2
4 3
4 4

Functions¶

  • A functions starts with keyword def
  • Very useful is the docstring, i.e., a string at the begining, which explains what the function does
  • Multiple things (classes or values) can be returned by tuples
  • function can have default and keyword arguments
In [47]:
def funca(s):
    """Print a string and tell how many characters it has.
       Returns the length
    """
    print(s,'has',len(s),'characters')
    return (len(s),s)
    
l,s = funca('something')

print(funca('This string'))
help(funca)
something has 9 characters
This string has 11 characters
(11, 'This string')
Help on function funca in module __main__:

funca(s)
    Print a string and tell how many characters it has.
    Returns the length

If we explicitly list the name of the arguments in the function calls, they do not need to come in the same order as in the function definition. This is called keyword arguments, and is often very useful in functions that takes a lot of optional arguments.

In [48]:
def funca(s,prnt=False,extra='p'):
    """Print a string with extra attached, 
    and returns new string.
    """
    sn = s+extra
    if prnt:
        print(sn,'has',len(sn),'characters')
    return sn

funca('This str',extra='q')
Out[48]:
'This strq'

Unnamed functions (lambda function)¶

In Python we can also create unnamed functions, using the lambda keyword:

In [49]:
def f2(x):
    return x**2

# is equivalent to

f1 = lambda x: x**2
In [50]:
f1(3), f2(3)
Out[50]:
(9, 9)

This technique is useful for example when we want to pass a simple function as an argument to another function, like this:

In [51]:
from scipy import integrate
help(integrate.quad)
Help on function quad in module scipy.integrate._quadpack_py:

quad(func, a, b, args=(), full_output=0, epsabs=1.49e-08, epsrel=1.49e-08, limit=50, points=None, weight=None, wvar=None, wopts=None, maxp1=50, limlst=50, complex_func=False)
    Compute a definite integral.
    
    Integrate func from `a` to `b` (possibly infinite interval) using a
    technique from the Fortran library QUADPACK.
    
    Parameters
    ----------
    func : {function, scipy.LowLevelCallable}
        A Python function or method to integrate. If `func` takes many
        arguments, it is integrated along the axis corresponding to the
        first argument.
    
        If the user desires improved integration performance, then `f` may
        be a `scipy.LowLevelCallable` with one of the signatures::
    
            double func(double x)
            double func(double x, void *user_data)
            double func(int n, double *xx)
            double func(int n, double *xx, void *user_data)
    
        The ``user_data`` is the data contained in the `scipy.LowLevelCallable`.
        In the call forms with ``xx``,  ``n`` is the length of the ``xx``
        array which contains ``xx[0] == x`` and the rest of the items are
        numbers contained in the ``args`` argument of quad.
    
        In addition, certain ctypes call signatures are supported for
        backward compatibility, but those should not be used in new code.
    a : float
        Lower limit of integration (use -numpy.inf for -infinity).
    b : float
        Upper limit of integration (use numpy.inf for +infinity).
    args : tuple, optional
        Extra arguments to pass to `func`.
    full_output : int, optional
        Non-zero to return a dictionary of integration information.
        If non-zero, warning messages are also suppressed and the
        message is appended to the output tuple.
    complex_func : bool, optional
        Indicate if the function's (`func`) return type is real
        (``complex_func=False``: default) or complex (``complex_func=True``).
        In both cases, the function's argument is real.
        If full_output is also non-zero, the `infodict`, `message`, and
        `explain` for the real and complex components are returned in
        a dictionary with keys "real output" and "imag output".
    
    Returns
    -------
    y : float
        The integral of func from `a` to `b`.
    abserr : float
        An estimate of the absolute error in the result.
    infodict : dict
        A dictionary containing additional information.
    message
        A convergence message.
    explain
        Appended only with 'cos' or 'sin' weighting and infinite
        integration limits, it contains an explanation of the codes in
        infodict['ierlst']
    
    Other Parameters
    ----------------
    epsabs : float or int, optional
        Absolute error tolerance. Default is 1.49e-8. `quad` tries to obtain
        an accuracy of ``abs(i-result) <= max(epsabs, epsrel*abs(i))``
        where ``i`` = integral of `func` from `a` to `b`, and ``result`` is the
        numerical approximation. See `epsrel` below.
    epsrel : float or int, optional
        Relative error tolerance. Default is 1.49e-8.
        If ``epsabs <= 0``, `epsrel` must be greater than both 5e-29
        and ``50 * (machine epsilon)``. See `epsabs` above.
    limit : float or int, optional
        An upper bound on the number of subintervals used in the adaptive
        algorithm.
    points : (sequence of floats,ints), optional
        A sequence of break points in the bounded integration interval
        where local difficulties of the integrand may occur (e.g.,
        singularities, discontinuities). The sequence does not have
        to be sorted. Note that this option cannot be used in conjunction
        with ``weight``.
    weight : float or int, optional
        String indicating weighting function. Full explanation for this
        and the remaining arguments can be found below.
    wvar : optional
        Variables for use with weighting functions.
    wopts : optional
        Optional input for reusing Chebyshev moments.
    maxp1 : float or int, optional
        An upper bound on the number of Chebyshev moments.
    limlst : int, optional
        Upper bound on the number of cycles (>=3) for use with a sinusoidal
        weighting and an infinite end-point.
    
    See Also
    --------
    dblquad : double integral
    tplquad : triple integral
    nquad : n-dimensional integrals (uses `quad` recursively)
    fixed_quad : fixed-order Gaussian quadrature
    simpson : integrator for sampled data
    romb : integrator for sampled data
    scipy.special : for coefficients and roots of orthogonal polynomials
    
    Notes
    -----
    For valid results, the integral must converge; behavior for divergent
    integrals is not guaranteed.
    
    **Extra information for quad() inputs and outputs**
    
    If full_output is non-zero, then the third output argument
    (infodict) is a dictionary with entries as tabulated below. For
    infinite limits, the range is transformed to (0,1) and the
    optional outputs are given with respect to this transformed range.
    Let M be the input argument limit and let K be infodict['last'].
    The entries are:
    
    'neval'
        The number of function evaluations.
    'last'
        The number, K, of subintervals produced in the subdivision process.
    'alist'
        A rank-1 array of length M, the first K elements of which are the
        left end points of the subintervals in the partition of the
        integration range.
    'blist'
        A rank-1 array of length M, the first K elements of which are the
        right end points of the subintervals.
    'rlist'
        A rank-1 array of length M, the first K elements of which are the
        integral approximations on the subintervals.
    'elist'
        A rank-1 array of length M, the first K elements of which are the
        moduli of the absolute error estimates on the subintervals.
    'iord'
        A rank-1 integer array of length M, the first L elements of
        which are pointers to the error estimates over the subintervals
        with ``L=K`` if ``K<=M/2+2`` or ``L=M+1-K`` otherwise. Let I be the
        sequence ``infodict['iord']`` and let E be the sequence
        ``infodict['elist']``.  Then ``E[I[1]], ..., E[I[L]]`` forms a
        decreasing sequence.
    
    If the input argument points is provided (i.e., it is not None),
    the following additional outputs are placed in the output
    dictionary. Assume the points sequence is of length P.
    
    'pts'
        A rank-1 array of length P+2 containing the integration limits
        and the break points of the intervals in ascending order.
        This is an array giving the subintervals over which integration
        will occur.
    'level'
        A rank-1 integer array of length M (=limit), containing the
        subdivision levels of the subintervals, i.e., if (aa,bb) is a
        subinterval of ``(pts[1], pts[2])`` where ``pts[0]`` and ``pts[2]``
        are adjacent elements of ``infodict['pts']``, then (aa,bb) has level l
        if ``|bb-aa| = |pts[2]-pts[1]| * 2**(-l)``.
    'ndin'
        A rank-1 integer array of length P+2. After the first integration
        over the intervals (pts[1], pts[2]), the error estimates over some
        of the intervals may have been increased artificially in order to
        put their subdivision forward. This array has ones in slots
        corresponding to the subintervals for which this happens.
    
    **Weighting the integrand**
    
    The input variables, *weight* and *wvar*, are used to weight the
    integrand by a select list of functions. Different integration
    methods are used to compute the integral with these weighting
    functions, and these do not support specifying break points. The
    possible values of weight and the corresponding weighting functions are.
    
    ==========  ===================================   =====================
    ``weight``  Weight function used                  ``wvar``
    ==========  ===================================   =====================
    'cos'       cos(w*x)                              wvar = w
    'sin'       sin(w*x)                              wvar = w
    'alg'       g(x) = ((x-a)**alpha)*((b-x)**beta)   wvar = (alpha, beta)
    'alg-loga'  g(x)*log(x-a)                         wvar = (alpha, beta)
    'alg-logb'  g(x)*log(b-x)                         wvar = (alpha, beta)
    'alg-log'   g(x)*log(x-a)*log(b-x)                wvar = (alpha, beta)
    'cauchy'    1/(x-c)                               wvar = c
    ==========  ===================================   =====================
    
    wvar holds the parameter w, (alpha, beta), or c depending on the weight
    selected. In these expressions, a and b are the integration limits.
    
    For the 'cos' and 'sin' weighting, additional inputs and outputs are
    available.
    
    For finite integration limits, the integration is performed using a
    Clenshaw-Curtis method which uses Chebyshev moments. For repeated
    calculations, these moments are saved in the output dictionary:
    
    'momcom'
        The maximum level of Chebyshev moments that have been computed,
        i.e., if ``M_c`` is ``infodict['momcom']`` then the moments have been
        computed for intervals of length ``|b-a| * 2**(-l)``,
        ``l=0,1,...,M_c``.
    'nnlog'
        A rank-1 integer array of length M(=limit), containing the
        subdivision levels of the subintervals, i.e., an element of this
        array is equal to l if the corresponding subinterval is
        ``|b-a|* 2**(-l)``.
    'chebmo'
        A rank-2 array of shape (25, maxp1) containing the computed
        Chebyshev moments. These can be passed on to an integration
        over the same interval by passing this array as the second
        element of the sequence wopts and passing infodict['momcom'] as
        the first element.
    
    If one of the integration limits is infinite, then a Fourier integral is
    computed (assuming w neq 0). If full_output is 1 and a numerical error
    is encountered, besides the error message attached to the output tuple,
    a dictionary is also appended to the output tuple which translates the
    error codes in the array ``info['ierlst']`` to English messages. The
    output information dictionary contains the following entries instead of
    'last', 'alist', 'blist', 'rlist', and 'elist':
    
    'lst'
        The number of subintervals needed for the integration (call it ``K_f``).
    'rslst'
        A rank-1 array of length M_f=limlst, whose first ``K_f`` elements
        contain the integral contribution over the interval
        ``(a+(k-1)c, a+kc)`` where ``c = (2*floor(|w|) + 1) * pi / |w|``
        and ``k=1,2,...,K_f``.
    'erlst'
        A rank-1 array of length ``M_f`` containing the error estimate
        corresponding to the interval in the same position in
        ``infodict['rslist']``.
    'ierlst'
        A rank-1 integer array of length ``M_f`` containing an error flag
        corresponding to the interval in the same position in
        ``infodict['rslist']``.  See the explanation dictionary (last entry
        in the output tuple) for the meaning of the codes.
    
    
    **Details of QUADPACK level routines**
    
    `quad` calls routines from the FORTRAN library QUADPACK. This section
    provides details on the conditions for each routine to be called and a
    short description of each routine. The routine called depends on
    `weight`, `points` and the integration limits `a` and `b`.
    
    ================  ==============  ==========  =====================
    QUADPACK routine  `weight`        `points`    infinite bounds
    ================  ==============  ==========  =====================
    qagse             None            No          No
    qagie             None            No          Yes
    qagpe             None            Yes         No
    qawoe             'sin', 'cos'    No          No
    qawfe             'sin', 'cos'    No          either `a` or `b`
    qawse             'alg*'          No          No
    qawce             'cauchy'        No          No
    ================  ==============  ==========  =====================
    
    The following provides a short description from [1]_ for each
    routine.
    
    qagse
        is an integrator based on globally adaptive interval
        subdivision in connection with extrapolation, which will
        eliminate the effects of integrand singularities of
        several types.
    qagie
        handles integration over infinite intervals. The infinite range is
        mapped onto a finite interval and subsequently the same strategy as
        in ``QAGS`` is applied.
    qagpe
        serves the same purposes as QAGS, but also allows the
        user to provide explicit information about the location
        and type of trouble-spots i.e. the abscissae of internal
        singularities, discontinuities and other difficulties of
        the integrand function.
    qawoe
        is an integrator for the evaluation of
        :math:`\int^b_a \cos(\omega x)f(x)dx` or
        :math:`\int^b_a \sin(\omega x)f(x)dx`
        over a finite interval [a,b], where :math:`\omega` and :math:`f`
        are specified by the user. The rule evaluation component is based
        on the modified Clenshaw-Curtis technique
    
        An adaptive subdivision scheme is used in connection
        with an extrapolation procedure, which is a modification
        of that in ``QAGS`` and allows the algorithm to deal with
        singularities in :math:`f(x)`.
    qawfe
        calculates the Fourier transform
        :math:`\int^\infty_a \cos(\omega x)f(x)dx` or
        :math:`\int^\infty_a \sin(\omega x)f(x)dx`
        for user-provided :math:`\omega` and :math:`f`. The procedure of
        ``QAWO`` is applied on successive finite intervals, and convergence
        acceleration by means of the :math:`\varepsilon`-algorithm is applied
        to the series of integral approximations.
    qawse
        approximate :math:`\int^b_a w(x)f(x)dx`, with :math:`a < b` where
        :math:`w(x) = (x-a)^{\alpha}(b-x)^{\beta}v(x)` with
        :math:`\alpha,\beta > -1`, where :math:`v(x)` may be one of the
        following functions: :math:`1`, :math:`\log(x-a)`, :math:`\log(b-x)`,
        :math:`\log(x-a)\log(b-x)`.
    
        The user specifies :math:`\alpha`, :math:`\beta` and the type of the
        function :math:`v`. A globally adaptive subdivision strategy is
        applied, with modified Clenshaw-Curtis integration on those
        subintervals which contain `a` or `b`.
    qawce
        compute :math:`\int^b_a f(x) / (x-c)dx` where the integral must be
        interpreted as a Cauchy principal value integral, for user specified
        :math:`c` and :math:`f`. The strategy is globally adaptive. Modified
        Clenshaw-Curtis integration is used on those intervals containing the
        point :math:`x = c`.
    
    **Integration of Complex Function of a Real Variable**
    
    A complex valued function, :math:`f`, of a real variable can be written as
    :math:`f = g + ih`.  Similarly, the integral of :math:`f` can be
    written as
    
    .. math::
        \int_a^b f(x) dx = \int_a^b g(x) dx + i\int_a^b h(x) dx
    
    assuming that the integrals of :math:`g` and :math:`h` exist
    over the interval :math:`[a,b]` [2]_. Therefore, ``quad`` integrates
    complex-valued functions by integrating the real and imaginary components
    separately.
    
    
    References
    ----------
    
    .. [1] Piessens, Robert; de Doncker-Kapenga, Elise;
           Überhuber, Christoph W.; Kahaner, David (1983).
           QUADPACK: A subroutine package for automatic integration.
           Springer-Verlag.
           ISBN 978-3-540-12553-2.
    
    .. [2] McCullough, Thomas; Phillips, Keith (1973).
           Foundations of Analysis in the Complex Plane.
           Holt Rinehart Winston.
           ISBN 0-03-086370-8
    
    Examples
    --------
    Calculate :math:`\int^4_0 x^2 dx` and compare with an analytic result
    
    >>> from scipy import integrate
    >>> import numpy as np
    >>> x2 = lambda x: x**2
    >>> integrate.quad(x2, 0, 4)
    (21.333333333333332, 2.3684757858670003e-13)
    >>> print(4**3 / 3.)  # analytical result
    21.3333333333
    
    Calculate :math:`\int^\infty_0 e^{-x} dx`
    
    >>> invexp = lambda x: np.exp(-x)
    >>> integrate.quad(invexp, 0, np.inf)
    (1.0, 5.842605999138044e-11)
    
    Calculate :math:`\int^1_0 a x \,dx` for :math:`a = 1, 3`
    
    >>> f = lambda x, a: a*x
    >>> y, err = integrate.quad(f, 0, 1, args=(1,))
    >>> y
    0.5
    >>> y, err = integrate.quad(f, 0, 1, args=(3,))
    >>> y
    1.5
    
    Calculate :math:`\int^1_0 x^2 + y^2 dx` with ctypes, holding
    y parameter as 1::
    
        testlib.c =>
            double func(int n, double args[n]){
                return args[0]*args[0] + args[1]*args[1];}
        compile to library testlib.*
    
    ::
    
       from scipy import integrate
       import ctypes
       lib = ctypes.CDLL('/home/.../testlib.*') #use absolute path
       lib.func.restype = ctypes.c_double
       lib.func.argtypes = (ctypes.c_int,ctypes.c_double)
       integrate.quad(lib.func,0,1,(1))
       #(1.3333333333333333, 1.4802973661668752e-14)
       print((1.0**3/3.0 + 1.0) - (0.0**3/3.0 + 0.0)) #Analytic result
       # 1.3333333333333333
    
    Be aware that pulse shapes and other sharp features as compared to the
    size of the integration interval may not be integrated correctly using
    this method. A simplified example of this limitation is integrating a
    y-axis reflected step function with many zero values within the integrals
    bounds.
    
    >>> y = lambda x: 1 if x<=0 else 0
    >>> integrate.quad(y, -1, 1)
    (1.0, 1.1102230246251565e-14)
    >>> integrate.quad(y, -1, 100)
    (1.0000000002199108, 1.0189464580163188e-08)
    >>> integrate.quad(y, -1, 10000)
    (0.0, 0.0)

In [52]:
from scipy import integrate
from numpy import *

def square(x):
    return x**2


print( integrate.quad(lambda x: sin(x)/x,0,1) )
print( integrate.quad(square, 0,1,) )
(0.946083070367183, 1.0503632079297087e-14)
(0.3333333333333333, 3.700743415417188e-15)

Classes¶

A class can contain attributes (variables) and methods (functions).

A class is defined by class keyword, and the class can contains a number of class method definitions (a function in a class).

  • Each class method should have an argument self as its first argument. This object is a self-reference.
  • Some class method names have special meaning, for example:
    • __init__ : Constructor, i.e., the name of the method that is invoked when the object is first created.
    • __str__ : A method that is invoked when a simple string representation of the class is needed, as for example when printed.
    • __repr__ : Representation of the class when printed
    • __call__ : Functor, i.e, called when the instance is “called” as a function
    • There are many more, see http://docs.python.org/2/reference/datamodel.html#special-method-names
    • Note: each class member starting with __ is private. If it does not start with __, it is public.
In [53]:
class Point:
    """
    Simple class for representing a point in a Cartesian coordinate system.
    """
    def __init__(self, x, y):
        """
        Create a new Point at x, y.
        """
        self.x = x
        self.y = y
        #print('you gave me x and y=', x, y)
    def translate(self, dx, dy):
        """
        Translate the point by dx and dy in the x and y direction.
        """
        self.x += dx
        self.y += dy
        self.t = 1.0
        
    def __str__(self):        
        return("Point at [%f, %f]" % (self.x, self.y))
    def __call__(self,z):
        return self.x,self.y,z
In [54]:
q = Point(2., 3.0)

q.translate(1,1)

print(q.x, q.y, q.t)
print(q)
q(4.5)
3.0 4.0 1.0
Point at [3.000000, 4.000000]
Out[54]:
(3.0, 4.0, 4.5)
In [55]:
p = Point(1.,2.)

print( p )

p.translate(1,1)

print(p)

print(p(1.0))

print(p.x,p.y)
Point at [1.000000, 2.000000]
Point at [2.000000, 3.000000]
(2.0, 3.0, 1.0)
2.0 3.0

A bit more advanced example of projectile motion:

In [56]:
import numpy as np
import pylab as plt

class Projectile:
    """
    A class to model projectile motion in 2D under gravity.

    Attributes
    ----------
    v0 : float
        The initial speed of the projectile (in meters per second).
    angle : float
        The launch angle in degrees.
    g : float
        The gravitational acceleration (default is 9.81 m/s^2).

    Methods
    -------
    time_of_flight():
        Returns the total time the projectile is in the air.
    max_height():
        Returns the maximum height reached by the projectile.
    horizontal_range():
        Returns the horizontal distance (range) traveled by the projectile.
    trajectory(num_points=100):
        Returns arrays of x and y positions along the projectile's path.
    plot_trajectory(num_points=100):
        Plots the trajectory of the projectile.
    """

    def __init__(self, v0, angle, g=9.81):
        """
        Initialize the Projectile with an initial speed, launch angle, and gravitational acceleration.
        Parameters
        ----------
        v0 : float
            The initial speed (m/s).
        angle : float
            The launch angle (in degrees).
        g : float, optional
            Gravitational acceleration (default is 9.81 m/s^2).
        """
        self.v0 = v0
        # Convert angle from degrees to radians for computation.
        self.angle = np.radians(angle)
        self.g = g

    def time_of_flight(self):
        "Calculate the total time in s the projectile spends in the air."
        return 2 * self.v0 * np.sin(self.angle) / self.g
    
    def max_height(self):
        "Calculate the maximum height reached by the projectile."
        
        return (self.v0**2 * np.sin(self.angle)**2) / (2 * self.g)

    def horizontal_range(self):
        "Calculate the horizontal range (distance) of the projectile."
        return (self.v0**2 * np.sin(2 * self.angle)) / self.g

    def __str__(self):
        "For conversion to string representation"
        return f"(v0={self.v0}, angle={np.degrees(self.angle)}, g={self.g})"
    
    def trajectory(self, num_points=100):
        """
        Compute the x and y coordinates along the projectile's trajectory.
        num_points : int, optional
            The number of points to compute along the trajectory (default is 100).

        Returns
        -------
        tuple of np.ndarray
            Two arrays (x, y) containing the horizontal and vertical positions.
        """
        t_flight = self.time_of_flight()
        t = np.linspace(0, t_flight, num_points)
        x = self.v0 * np.cos(self.angle) * t
        y = self.v0 * np.sin(self.angle) * t - 0.5 * self.g * t**2
        return x, y

    def plot_trajectory(self, num_points=100):
        """
        Plot the projectile's trajectory.

        Parameters
        ----------
        num_points : int, optional
            The number of points to compute for the trajectory (default is 100).
        """
        x, y = self.trajectory(num_points)
        plt.plot(x, y, label=f'v0 = {self.v0} m/s, angle = {np.degrees(self.angle):.1f}°')
        plt.xlabel('Horizontal Distance (m)')
        plt.ylabel('Vertical Height (m)')
        plt.title('Projectile Motion Trajectory')
        plt.legend()
        plt.grid(True)
        plt.show()
In [57]:
# Create a projectile with an initial speed of 50 m/s and a launch angle of 45 degrees.
proj = Projectile(v0=50, angle=45)

print('Projectile is', proj)
# Compute and print various properties.
print("Time of Flight:", proj.time_of_flight(), "seconds")
print("Maximum Height:", proj.max_height(), "meters")
print("Horizontal Range:", proj.horizontal_range(), "meters")

# Plot the trajectory.
proj.plot_trajectory(num_points=200)
Projectile is (v0=50, angle=45.0, g=9.81)
Time of Flight: 7.208020195581523 seconds
Maximum Height: 63.71049949031599 meters
Horizontal Range: 254.841997961264 meters
No description has been provided for this image

Modules¶

For additional modularity, modules are provided in Python.

The modularity in Python is:

  • variables, functions
  • classes, which combine variables and functions
  • modules, which combine classes, variables and functions into a unit, usually a file

Module is a python file (*.py) or a module created by compiler (*.so)

Outside jupyter (in regular python) we just create a file with the code, and call it a module.

Within jupyter, we need to write code into a file, and than load the module (file).

In [58]:
%%file mymodule.py  
# This will write the following content into a file
"""
Example of a python module. Contains a variable called my_variable,
a function called my_function, and a class called MyClass.
"""

my_variable = 0

def my_function():
    """
    Example function
    """
    return my_variable
    
class MyClass:
    """
    Example class.
    """

    def __init__(self):
        self.variable = my_variable
        
    def set_variable(self, new_value):
        """
        Set self.variable to a new value
        """
        self.variable = new_value
        
    def get_variable(self):
        return self.variable
   
print(__name__)

if __name__ == '__main__':
    "test the module"
    m = MyClass()
    m.set_variable(1.)
    print(m.get_variable())
Overwriting mymodule.py
In [59]:
!cat mymodule.py
# This will write the following content into a file
"""
Example of a python module. Contains a variable called my_variable,
a function called my_function, and a class called MyClass.
"""

my_variable = 0

def my_function():
    """
    Example function
    """
    return my_variable
    
class MyClass:
    """
    Example class.
    """

    def __init__(self):
        self.variable = my_variable
        
    def set_variable(self, new_value):
        """
        Set self.variable to a new value
        """
        self.variable = new_value
        
    def get_variable(self):
        return self.variable
   
print(__name__)

if __name__ == '__main__':
    "test the module"
    m = MyClass()
    m.set_variable(1.)
    print(m.get_variable())
In [60]:
import mymodule as my
import scipy as sy
#help(mymodule)
mymodule
In [61]:
m = my.MyClass()
m.set_variable(10)
m.get_variable()
Out[61]:
10
In [ ]: