Python Tutorial m7Ou6Vm
Python Tutorial m7Ou6Vm
You need to install the following additional libraries to run the cells in this Notebook.
1. numpy
2. scipy
3. matplotlib
You can upload this file on Google Colabs and run the cells. You will have to login
with your google account. All the relevant libraries are generally available on Colabs.
<class 'int'>
In [2]: A = 6.0
print(type(A))
<class 'float'>
a = 2
A = 6.0
In [14]: print(y, z, Z)
print(type(y))
print(type(Z))
3.54 0.3333333333333333 1
<class 'float'>
<class 'int'>
In [15]: c = 2 + 4j
type(c)
Out[15]: complex
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 1 of 32
Python_Tutorial 12/01/25, 12:12 PM
Using modules
In [16]: import math
In [17]: print(math.pi)
3.141592653589793
Out[20]: 6.62607015e-34
A = np.matrix(A)
print(type(A))
print(A.shape)
<class 'list'>
<class 'numpy.matrix'>
(2, 2)
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 2 of 32
Python_Tutorial 12/01/25, 12:12 PM
Out[25]: (1, 5)
Out[29]: (4, 1)
[[1 2]
[2 4]]
1
[[1 2]]
2
In [27]: print(Xlist)
print(Xlist[1:])
print(Xlist[:-1])
In [28]: print(A)
print(A[0, 0:2]) # the upper limit 2 is not included
[[1 2]
[2 4]]
[[1 2]]
Specific functions
arange , linspace , and logspace
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9]
[0. 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1. ]
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 3 of 32
Python_Tutorial 12/01/25, 12:12 PM
np.logspace(logx1, logx2, n)
logx1 = −1 (1)
logx2 = 2 (2)
n=4 (3)
In [32]: np.logspace(-1, 2, 4)
Mathematical operations
(Image from Chapra and Clough)
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 4 of 32
Python_Tutorial 12/01/25, 12:12 PM
Out[24]: 0.19634954084936207
0.19634954084936207
In [35]: x = 3; y = 2; z = 1.5
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 5 of 32
Python_Tutorial 12/01/25, 12:12 PM
-x ** y
Out[35]: -9
In [36]: (-x)**y
Out[36]: 9
In [30]: x ** y ** z
Out[30]: 22.361590938430393
In [31]: x**(y**z)
Out[31]: 22.361590938430393
In [32]: (x**y)**z
Out[32]: 27.0
Out[37]: (1, 5)
Out[38]: (5, 1)
Out[39]: matrix([[110]])
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 6 of 32
Python_Tutorial 12/01/25, 12:12 PM
a = np.matrix('1 2 3');
b = np.matrix('4; 5; 6')
In [43]: a*A
In [45]: A*b
--------------------------------------------------------------------------
-
ValueError Traceback (most recent call last
)
Cell In[36], line 1
----> 1 A*a # you will get an error
File ~/miniconda3/envs/fenics2019.1/lib/python3.9/site-packages/numpy/matr
ixlib/defmatrix.py:221, in matrix.__mul__(self, other)
218 def __mul__(self, other):
219 if isinstance(other, (N.ndarray, list, tuple)) :
220 # This promotes 1-D vectors to row vectors
--> 221 return N.dot(self, asmatrix(other))
222 if isscalar(other) or not hasattr(other, '__rmul__') :
223 return N.dot(self, other)
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 7 of 32
Python_Tutorial 12/01/25, 12:12 PM
Out[48]: 38
Using help
Using [command]? . Generally very unhelpful. Better if used with LLM.
Built-in functions
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 8 of 32
Python_Tutorial 12/01/25, 12:12 PM
v=√ tanh(√
mg cd g
cd m t)
49.42136691869133
t = 10
v = velocity(t)
print(v)
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 9 of 32
Python_Tutorial 12/01/25, 12:12 PM
print('{0:5.6f}'.format(v))
print('velocity = ', v, 'm/s')
49.42136691869133
49.421367
velocity = 49.42136691869133 m/s
Vectorization of output
In [10]: print(type(tm))
print(type(np.array([0, 1, 2])))
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 10 of 32
Python_Tutorial 12/01/25, 12:12 PM
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 11 of 32
Python_Tutorial 12/01/25, 12:12 PM
#plt.plot(tm, v, marker='o')
plt.scatter(tm, v)
plt.title("Velocity as a function of time")
plt.xlabel('Time in seconds')
plt.ylabel('Velocity in m/s')
plt.grid()
cd = 0.35
v1 = np.sqrt(m*g/cd)*np.tanh(np.sqrt(cd*g/m)*tm)
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 12 of 32
Python_Tutorial 12/01/25, 12:12 PM
Coding in Python
You can write the commands and save them in filename.py . Then run the
command python filename.py . Else work everything in jupyter notebook
Python functions - 1
def function_name(arguments):
statements
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 13 of 32
Python_Tutorial 12/01/25, 12:12 PM
Out[16]: 50.608007473466444
Another function
8 7.125 2.5708704751503917
Variable scope
In the function below x is defined outside the function but is accessible from within.
However, s is defined inside the function and is not accessible from outside. In a
call to the previous function stats we had calculated s .
In [5]: s
Out[5]: np.float64(2.5708704751503917)
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 14 of 32
Python_Tutorial 12/01/25, 12:12 PM
f = s;
return s
x = 88
c = 1
d = 5
print('sum = ', adder(c, d))
print('s = ', s)
print('f = ', f)
x = 88
sum = 6
s = 2.5708704751503917
--------------------------------------------------------------------------
-
NameError Traceback (most recent call last
)
Cell In[6], line 14
12 print('sum = ', adder(c, d))
13 print('s = ', s)
---> 14 print('f = ', f)
However, we can define a variable within a function with a global scope in which case
it can be made accessible from outside.
c = 1
d = 5
print('sum = ', adder(c, d))
print('x = ', x)
print('s = ', s)
sum = 6
x = 90
s = 10
Input-Output
s = input('prompt string')
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 15 of 32
Python_Tutorial 12/01/25, 12:12 PM
20 123.456 10
12.3 45.678000
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 16 of 32
Python_Tutorial 12/01/25, 12:12 PM
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 17 of 32
Python_Tutorial 12/01/25, 12:12 PM
import numpy as np
time,x,y = np.loadtxt('testdata.csv',unpack=True,delimiter=',')
X = np.array([time,x,y]).transpose()
np.save('Xdata.npy',X)
X2=np.load('Xdata.npy')
print(X2)
[[ 0. -0.109 53.8 ]
[ 9. 0. 53.6 ]
[18. 0.178 53.5 ]
[27. 0.339 53.5 ]
[36. 0.373 53.4 ]
[45. 0.441 53.1 ]
[54. 0.461 52.7 ]
[63. 0.348 52.4 ]
[72. 0.127 52.2 ]
[81. -0.18 52. ]
[90. -0.588 52. ]]
Structured Programming
1. Decisions (selection)
2. Loops (repetition)
if condition: statements
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 18 of 32
Python_Tutorial 12/01/25, 12:12 PM
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 19 of 32
Python_Tutorial 12/01/25, 12:12 PM
Out[21]: 1.0
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 20 of 32
Python_Tutorial 12/01/25, 12:12 PM
In [22]: np.sign(-1.76)
Out[22]: -1.0
In [5]: np.sign(0)
Out[5]: 0
In [ ]: if x > 0
{
return 1
}
In [23]: # one-way if
def sgn(x):
if x > 0:
print('x = ', x)
return 1
print(sgn(-1))
None
In [24]: # two-way if
def sgn(x):
if x > 0:
return 1
else:
return -1
print(sgn(-1))
print(sgn(0))
-1
-1
In [27]: # multi-alternative if
def sgn(x):
print('x = ', x)
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
print(sgn(0))
x = 0
0
Loops
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 21 of 32
Python_Tutorial 12/01/25, 12:12 PM
1
4
7
10
M1
M2
M3
M4
0
1
2
3
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 22 of 32
Python_Tutorial 12/01/25, 12:12 PM
def factor(n):
"""
computes the product of all the integers from 1 to n
special case: factor(0) = 1
"""
x = 1
for i in range(n):
print(i)
x = x * (i + 1)
return x
factor(5)
#print(factor(0))
#print(factor(1))
#print(factor(5))
#print(factor(20))
0
1
2
3
4
Out[34]: 120
Vectorization
In [49]: import numpy as np
y = np.zeros(2501)
time = np.zeros(2501)
print(y)
print(len(y))
for i in range(2501):
t = i * 0.02
time[i] = t
y[i] = np.cos(t)
import matplotlib.pyplot as plt
plt.plot(time, y)
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 23 of 32
Python_Tutorial 12/01/25, 12:12 PM
In [44]: print(y)
In [35]: y1 = np.zeros(2501)
t = np.arange(0., 50.02, 0.02)
y1 = np.cos(t)
plt.plot(t, y1)
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 24 of 32
Python_Tutorial 12/01/25, 12:12 PM
While loop
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 25 of 32
Python_Tutorial 12/01/25, 12:12 PM
In [43]: x = 100
while True:
if x < 0: break
x = x - 5
print(x)
-5
In [44]: x = 100
while x >= 0:
x = x-5
print(x)
-5
In [45]: x = 100
while True:
x = x - 5
if x < 0: break
print(x)
-5
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 26 of 32
Python_Tutorial 12/01/25, 12:12 PM
x = 126.20381360535328
x = 126.20381360535328 i = 1
x = 123.70336483657101
x = 123.70336483657101 i = 2
x = 120.85369259534458
x = 120.85369259534458 i = 3
x = 104.49249930925347
x = 104.49249930925347 i = 4
x = 140.73584980774726
x = 140.73584980774726 i = 5
x = 103.59025400011168
x = 103.59025400011168 i = 6
x = 94.24750480680932
x = 102.18446902325981
x = 102.18446902325981 i = 7
x = 87.32039569615317
x = 108.70383121532561
x = 108.70383121532561 i = 8
x = 85.34851390963848
x = 128.23985572869233
x = 128.23985572869233 i = 9
x = 125.58436154566985
x = 125.58436154566985 i = 10
118.4291991667329
10
Nesting of structures
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 27 of 32
Python_Tutorial 12/01/25, 12:12 PM
input:
a = second order coefficient
b = first order coefficient
c = zero order coefficient
output:
r1 = real part of the first root
r2 = real part of the second root
i1 = imaginary part of the first root
i2 = imaginary part of the second root
"""
import math
print(math.sqrt(10))
if a == 0:
# special cases
if b != 0:
r1 = -c/b
return r1
else:
# trivial solution
print("Trivial solution. Try again")
else:
# quadratic formula
d = b**2 - 4*a*c
if d >= 0:
# real roots
print(d)
r1 = (-b + math.sqrt(d))/(2*a)
r2 = (-b - math.sqrt(d))/(2*a)
i1 = 0
i2 = 0
else:
# complex roots
r1 = -b/(2*a)
r2 = r1
i1 = math.sqrt(abs(d))/(2*a)
i2 = -math.sqrt(abs(d))/(2*a)
return r1, i1, r2, i2
In [41]: quadroots(1, 4, 1)
3.1622776601683795
12
Out[41]: (-0.2679491924311228, 0, -3.732050807568877, 0)
Out[53]: 3.1622776601683795
Lambda functions
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 28 of 32
Python_Tutorial 12/01/25, 12:12 PM
Out[56]: 25
In [57]: a = 4; b = 2
f2 = lambda x: a*x**b
f2(3)
Out[57]: 36
def f(w):
return np.sin(w)*np.cosh(w) - 5
fmid = midpoint(f, 0, 3)
print('function value at midpoint = ', fmid)
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 29 of 32
Python_Tutorial 12/01/25, 12:12 PM
Out[60]: 3.596809429094953
print(func(12, cd=0.3))
print(func(12, m=100)) # disregards third argument
print(func(12, 70, 0.25))
print(func(12))
print(func(12, 0.25))
47.15084308112941
59.78698843813102
51.24944572226363
51.24944572226363
3.132091952673165
51.24944572226363
51.24944572226363
51.24944572226363
51.24944572226363
3.0688108446106614
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 30 of 32
Python_Tutorial 12/01/25, 12:12 PM
output:
favg = average value of the function
"""
x = np.linspace(a, b, n)
y = f(x, *args)
favg = np.average(y)
return favg
36.013
output:
favg = average value of the function
"""
x = np.linspace(a, b, n)
y = f(x, **kwargs)
favg = np.average(y)
return favg
36.013
For a more detailed discussion on args and kwargs see the following link.
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 31 of 32
Python_Tutorial 12/01/25, 12:12 PM
This finishes the basic tutorial on Python programming. For a more thorough
discussion take a look at any of the references provided on BodhiTree. Below is an
example for combined
output:
favg = average value of the function
"""
x = np.linspace(a, b, n)
y = f(x, *args, **kwargs)
favg = np.average(y)
return favg
36.013
The scope of the language is vast. Learn more using the resources that I have
provided. You can also use one of the AI tools to write to code or debug it.
In [ ]:
http://localhost:8888/nbconvert/html/Python_Tutorial.ipynb?download=false Page 32 of 32