Lecture 1: Introduction to Python
M. Asif Farooq
1 / 18
What is Python language?
Python is open source software, which means it is available for
free.
Python is an interpreted language, meaning that it can run code
without the need for a compiler.
Python is a programming language that is used for scientific and
engineering computations all around the world.
Python is used when it comes to data analysis, machine learning,
and AI.
2 / 18
Installing Python
Since Python is free so there are many softwares available that
runs Python.
Some of these softwares are Spyder, Pyscripter etc
You can also type command on Jupyter notebooks available
online.
3 / 18
Checking Curren Version in Spyder
1 import platform
2 platform.python_version()
4 / 18
Interactive Python as a Calculator
In [1]: 2*3
Out[1]: 6
In [2]: 6 + 21/3
Out[2]: 13.0
In [3]: (6 + 21)/3
Out[3]: 9.0
5 / 18
Binary Arithmetic Operations in Python
operation Symbol
addition +
subtraction -
multiplication *
division /
floor division //
remainder %
exponentiation **
Table: Binary Operators.
6 / 18
Types of Numbers
Integers
Floating Point
Complex Numbers
In [4]: 12*3
Out[4]: 36
In [5]: 4 + 5*6-(21*8)
Out[5]: -134
In [6]: 11/5
Out[6]: 2.2
In [7]: 11//5
Out[7]: 2
In [8]: 9734828*79372
Out[8]: 772672768016
7 / 18
Types of Numbers (Cont.)
In [9]: 12.*3
Out[9]: 36.0
In [10]: 5**0.5
Out[10]: 2.23606797749979
In [11]: 11./5
Out[11]: 2.2
In [12]: 11.//5
Out[12]: 2.0
In [13]: 11.%5
Out[13]: 1.0
In [22]: 6.022e23*300
Out[22]: 1.8066e+26
8 / 18
Types of Numbers (Cont.)
In [24]: (2+3j)*(-4 + 9j)
Out[24]: (-35+6j)
In [25]: (2+3j)/(-4+9j)
Out[25]: (0.1958762886597938-0.3092783505154639j)
In [26]: 2.5 - 3j**2
Out[26]: (11.5+0j)
In [27]: (2.5 - 3j)**2
Out[27]: (-2.75-15j)
9 / 18
Variables
In [1]: a = 23
In [2]: p, q = 83.4, 2**0.5
In [3]: a = a + 1
In [4]: a
Out[4]: 24
In [5]: c, d = 4, 7.92
In [6]: c+= 2
In [7]: c
Out[7]: 6
In [8]: c*=3
In [9]: c
Out[9]: 18
In [10]: d/=-2
In [11]: d
Out[11]: -3.96
10 / 18
Script Files and Programs
Code: mytrip.py
d i s t a n c e = 400 #miles
mpg = 30 # c a r mileage
speed = 60 # average speed
c o s t p e r g a l l o n =2.85
t i m e = d i s t a n c e / speed
g a l l o n s = d i s t a n c e / mpg
cost = gallons * costpergallon
Run above code by typing %run mytrip.py on console
Then type time, gallons, cost
You can change the number of digits by %precision 2
Type %precision returns IPython to its default state
%precision %e displays numbers in exponential format
11 / 18
Note About Printing
To return value of the variable on the screen use print
print(time)
print(gallons)
print(cost)
12 / 18
Python Module
Python consist of supplementary modules
NumPy It is the standard Python package for scientific computing
with Python
SciPy provides a wide spectrum of mathematical functions and
numerical routines for Python.
matplotlib It is the stadard Python package for making two and
three dimensional lots.
Pandas It is a Python package providing a powerful set of data
analysis tools.
13 / 18
Python Modules and Functions
In [36]: import numpy
In [37]: numpy.sin(0.5)
Out[37]: 0.479425538604203
In [38]: import math
In [39]: math.sin(0.5)
Out[39]: 0.479425538604203
In [40]: numpy.sin(3+4j)
Out[40]: (3.853738037919377-27.016813258003932j)
In [41]: math.sin(3+4j)
Traceback (most recent call last):
File "C:1 5992870784069.py ”, line1, in < cellline : 1 > math.sin(3 + 4j)
TypeError: can’t convert complex to float
14 / 18
Python Modules and Functions
In [1]: import numpy as np
In [2]: np.sin(0.5)
Out[2]: 0.479425538604203
In [3]: np.sqrt(2)
Out[3]: 1.4142135623730951
In [4]: np.exp(2)
Out[4]: 7.38905609893065
In [5]: np.log(3)
Out[5]: 1.0986122886681098
In [6]: np.log10(2)
Out[6]: 0.3010299956639812
In [7]: np.degrees(1.47)
Out[7]: 84.22479588423101 15 / 18
Some NumPy Math Functions
sqrt(x) square root
exp(x) exponential of x
log(x) natural log of x
log10(x) base 10 log
degrees(x) converts x from radians to degrees
radians(x) converts x from degrees to radians
sin(x) sin of x (x in radians)
cos(x) cos of x (x in radians)
tan(x) tan of x (x in radians)
arcsin(x) inverse sin of x
arccos(x) arc cosine of x
arctang(x) arc tanent of x
fabs(x) absolute value of x
math.factorial(n) factorial of integer
round(x) rounds a float to nearest integer
floor(x) rounds a float down to nearest integer
ceil(x) rounds a float up to nearest integer 16 / 18
Scripting Example
code: Distance between in two points
i m p o r t numpy as np
x1 , y1 , z1 = 2 3 . 7 , −9.2 , −7.8
x2 , y2 , z2 = −3.5 , 4 . 8 , 8.1
d r = np . s q r t ( ( x2− x1 ) * * 2 + ( y2 − y1 ) * * 2 + ( z2− z1 ) * * 2 )
17 / 18
Different Ways of Importing Modules
import math
import numpy as np
from numpy import log
from numpy import log, sin, cos
18 / 18
Lecture 4
Data Structures in Python Programming:
String
M. Asif Farooq
1 / 12
Data Structures
Python stores and organize numerical, alphabetical and other
types of information.
In Python data structures include strings, lists, tuples and
dictionaries which are all part of core Python.
NumPy arrays is also used for storing and manipulating scientific
data.
NumPy arrays represent vectors, matrices and even tensors.
2 / 12
What is a String?
Strings are lists of characters.
Strings are created by enclosing a characters within a pair of
single or double quotes i.e. ’Hello’, "It’s a good day" etc
Strings can be assigned to the variable
3 / 12
Examples
In [1]: a = "my name is Asif"
In [2]: b = "I teach mathematics"
In [3]: c = a + b
In [4]: c
Out[4]: ’my name is AsifI teach mathematics’
In [5]: c = a + ". " b
File
"C:8 292668584637.py ”, line1c = a + ”.”bS yntaxError : invalidsyntax
In [6]: c = a + ". "+ b
In [7]: c
Out[7]: ’my name is Asif. I teach mathematics’
4 / 12
Interactive Python as a Calculator
In [8]: d = "23"
In [9]: e = 23
In [10]: type(d)
Out[10]: str
In [11]: type(e)
Out[11]: int
In above d is a string
In above e is an integer
5 / 12
Indices
The position or index of a character in Python is identified with the
numbering 0, 1, 2, 3, ....
Figure: Indexing in String.
6 / 12
Indexing: Examples
In [1]: a = "spam & eggs"
In [2]: a[0]
Out[2]: ’s’
In [3]: a[1]
Out[3]: ’p’
In [4]: a[2]
Out[4]: ’a’
In [5]: a[3]
Out[5]: ’m’
In [6]: a[4]
Out[6]: ’ ’
In [7]: a[5]
Out[7]: ’&’ 7 / 12
Substring or Slice
A substring or slice of a string is a sequence of consecutive
characters from the string.
Figure: Substring or slice.
8 / 12
Substring: Examples
In [8]: b = "Just a moment"
In [9]: b[0:4]
Out[9]: ’Just’
In [10]: b[1:4]
Out[10]: ’ust’
In [11]: b[2:5]
Out[11]: ’st ’
9 / 12
Substring: Examples (Cont.)
In [1]: c = "Python"
In [2]: c[0:2]
Out[2]: ’Py’
In [3]: c[0:6]
Out[3]: ’Python’
In [4]: c[0:1]
Out[4]: ’P’
10 / 12
Substring: Examples(Cont.)
In [1]: "Python"[1]
Out[1]: ’y’
In [2]: str1 = "Hello World!"
In [3]: str1.find(’W’)
Out[3]: 6
In [4]: str1.find(’x’)
Out[4]: -1
In [5]: str1.find(’l’)
Out[5]: 2
In [6]: str1.rfind(’l’)
Out[6]: 9
11 / 12
Negative Indices in String
In [7]: a = "spam & eggs"
In [8]: a[-2]
Out[8]: ’g’
In [9]: a[-8:-3]
Out[9]: ’m e’
In [10]: a[0:-1]
Out[10]: ’spam egg’
Figure: Negative Indices of the characters of the string.
12 / 12
Lecture 5
Data Structures in Python Programming:
Lists
M. Asif Farooq
1/9
Lists
Python has two data structures: lists and tuples.
A list is an ordered sequence of Python objects.
Lists are defined by a pair of square brackets surrounded by
elements.
Elements should be separated by comma otherwise one get error.
Lists are zero indexed like c but unlike MATLAB and Fortran which
are one indexed.
2/9
Lists: Examples
In [8]: a = [0, 1,1, 2, 3, 4]
In [9]: b = [2, "student", 3, "horse", "animal"]
In [10]: b[1]
Out[10]: ’student’
In [11]: b[4]
Out[11]: ’animal’
In [12]: b[-1]
Out[12]: ’animal’
In [13]: b[-2]
Out[13]: ’horse’
3/9
Lists: Examples (Cont.)
In [9]: b = [2, "student", 3, "horse", "animal"]
In [14]: b[-3]
Out[14]: 3
In [15]: b[-4]
Out[15]: ’student’
In [16]: b[-5]
Out[16]: 2
4/9
Lists: Examples (Cont.)
In [19]: b = [4, 5, "boys"]
In [20]: b[0] = b[0] + 3
In [21]: b[2] = b[2] + " and girls"
In [22]: b
Out[22]: [7, 5, ’boys and girls’]
In [23]: b+b
Out[23]: [7, 5, ’boys and girls’, 7, 5, ’boys and girls’]
In [24]: a = ["vegetable", "fruits", 4]
In [25]: a + b
Out[25]: [’vegetable’, ’fruits’, 4, 7, 5, ’boys and girls’]
5/9
Slicing Lists: Examples
In [27]: a = ["vegetable", "fruits", 4]
In [28]: a[0:1]
Out[28]: [’vegetable’]
In [29]: a[0:]
Out[29]: [’vegetable’, ’fruits’, 4]
In [31]: a[:2]
Out[31]: [’vegetable’, ’fruits’]
In [32]: a[:3]
Out[32]: [’vegetable’, ’fruits’, 4]
6/9
Slicing Lists: Examples (Cont.)
In [33]: a[:]
Out[33]: [’vegetable’, ’fruits’, 4]
In [34]: a[1:-1]
Out[34]: [’fruits’]
In [35]: len(a)
Out[35]: 3
In [36]: a[0::2]
Out[36]: [’vegetable’, 4]
7/9
Range Function
In [38]: list(range(10))
Out[38]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [39]: list(range(3,10))
Out[39]: [3, 4, 5, 6, 7, 8, 9]
In [40]: list(range(0,10,2))
Out[40]: [0, 2, 4, 6, 8]
In [41]: a = list(range(4,12))
In [42]: a
Out[42]: [4, 5, 6, 7, 8, 9, 10, 11]
8/9
Range Function (Cont.)
In [43]: b = list(range(-5, 5, 2))
In [44]: b
Out[44]: [-5, -3, -1, 1, 3]
In [45]: c = list(range(5,0,-1))
In [46]: c
Out[46]: [5, 4, 3, 2, 1]
9/9
Lecture 6
Data Structures in Python Programming:
Tuples
M. Asif Farooq
1/8
Mutable and Immutable Objects
An object holds the data and has operations that can manipulate
the data.
Numbers, strings, lists and tuples are objects.
Objects that can be changed in places are called mutable.
Objects that cannot be changed in place are called immutable.
2/8
Defining Tuples
Tuples are immutable
The items should be written in parentheses.
The elements should be separated by comma.
3/8
Tuples: Examples
In [54]: t = (3, 4 , 5)
In [55]: print(len(t))
3
In [56]: print(max(t))
5
In [57]: print(min(t))
3
In [58]: print(sum(t))
12
In [59]: t[0]
Out[59]: 3
In [60]: t[0] = t[0] + 3
Traceback (most recent call last):
File "C:1 2760786003402.py ”, line1, in < cellline : 1 >
t[0] = t[0] + 3
TypeError: ’tuple’ object does not support item assignment
4/8
Comments on Tuples
The tuple function converts lists or strings to lists.
Tuples are more efficient than lists and should be used in
situations where no changes will be made to the items.
An important feature of Python is dictionary. The dictionary
requires the use of tuples.
5/8
Examples: Converting Lists or Strings into Tuples
In [1]: tuple([’fruits’, ’vegetables’])
Out[1]: (’fruits’, ’vegetables’)
In [2]: tuple([2, ’students’])
Out[2]: (2, ’students’)
In [3]: tuple("spam")
Out[3]: (’s’, ’p’, ’a’, ’m’)
In [7]: a[0] + ’t’
Out[7]: ’st’
In [8]: a[0] = a[0] + ’t’
Traceback (most recent call last):
File "C:1 54450862836.py ”, line1, in < cellline : 1 > a[0] = a[0] +′ t ′
TypeError: ’tuple’ object does not support item assignment
6/8
Examples
In [17]: L = [5,6]
In [18]: L.append(7)
In [19]: L
Out[19]: [5, 6, 7]
In [20]: n = 2
In [21]: n+=1
In [22]: n
Out[22]: 3
In [23]: s = "Python"
In [24]: s = s.upper()
In [25]: s
Out[25]: ’PYTHON’
In [26]: t = (’a’, ’b’, ’c’)
In [27]: t = t[1:]
In [28]: t
Out[28]: (’b’, ’c’)
7/8
Examples: Tuples
In [10]: t = (2,3,1,3)
In [11]: print(t[1])
3
In [12]: t.index(3)
Out[12]: 1
In [15]: t.count(3)
Out[15]: 2
In [16]: len(t)
Out[16]: 4
In [17]: sum(t)
Out[17]: 9
In [18]: t + (7,5)
Out[18]: (2, 3, 1, 3, 7, 5)
In [19]: t*2
Out[19]: (2, 3, 1, 3, 2, 3, 1, 3)
8/8
Lecture 7
Data Structures in Python Programming:
Multidimensional Lists and Tuples
M. Asif Farooq
1/4
Multidimensional Lists and Tuples
In Python we can construct multidimensional lists or lists of lists
2/4
Examples
In [62]: a = [[2, 3], [4 , 5]
In [63]: a[0]
Out[63]: [2, 3]
In [64]: a[1]
Out[64]: [4, 5]
In [65]: a[1][0]
Out[65]: 4
In [66]: a[1][1]
Out[66]: 5
In [67]: a[1][-1]
Out[67]: 5
In [68]: a[1][-2]
Out[68]: 4
In [69]: a[0][0]
Out[69]: 2
3/4
Examples
In [71]: regions = [("Northeast", 55.3), ("Midwest", 66.9), ("South",
114.6) ]
In [72]: regions[0]
Out[72]: (’Northeast’, 55.3)
In [73]: regions[0][0]
Out[73]: ’Northeast’
In [74]: regions[0][1]
Out[74]: 55.3
In [75]: regions[1]
Out[75]: (’Midwest’, 66.9)
In [76]: regions[1][1]
Out[76]: 66.9
In [77]: regions[2][1]
Out[77]: 114.6
4/4
Lecture 8
NumPy Arrays
M. Asif Farooq
1/6
Creating Arrays in One Dimension
Python have different ways to create arrays.
The first method is by using array function.
The second method is by using NumPy linspace or logspace.
The third way is to use NumPy arange function.
The fourth way is to create arrays by zeros and ones.
2/6
Examples
In [79]: a = [0, 3, 5, 6]
In [80]: import numpy as np
In [81]: b = np.array(a)
In [82]: b
Out[82]: array([0, 3, 5, 6])
In [83]: c = np.array([1., -4., 5, 6])
In [84]: c
Out[84]: array([ 1., -4., 5., 6.])
3/6
Examples
In [86]: np.linspace(0, 10, 4)
Out[86]: array([ 0. , 3.33333333, 6.66666667, 10. ])
In [87]: np.linspace(-1, 2, 5)
Out[87]: array([-1. , -0.25, 0.5 , 1.25, 2. ])
In [90]: np.logspace(0, 10, 4)
Out[90]: array([1.00000000e+00, 2.15443469e+03, 4.64158883e+06,
1.00000000e+10])
4/6
Examples
In [95]: np.arange(0, 10, 2)
Out[95]: array([0, 2, 4, 6, 8])
In [96]: np.arange(0., 10, 2)
Out[96]: array([0., 2., 4., 6., 8.])
In [97]: np.arange(0, 10, 1.5)
Out[97]: array([0. , 1.5, 3. , 4.5, 6. , 7.5, 9. ])
In [98]: np.arange(0, 10)
Out[98]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [99]: np.arange(10)
Out[99]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
5/6
Examples
In [101]: np.zeros(6)
Out[101]: array([0., 0., 0., 0., 0., 0.])
In [102]: np.ones(6)
Out[102]: array([1., 1., 1., 1., 1., 1.])
6/6
Lecture 9
NumPy Arrays: Multidimensional Arrays and
Matrices
M. Asif Farooq
1/8
Creating Arrays in Higher Dimensions
NumPy arrays can be used to represent multidimensional arrays.
It means that we can create matrices.
Matrices can be represented with two-dimensional NumPy arrays.
Higher dimension arrays can also be created
2/8
Creating Matrices
In [2]: import numpy as np
In [3]: b = np.array([[1., 4, 5], [9,7,4]])
In [4]: b
Out[4]: array([[1., 4., 5.], [9., 7., 4.]])
In [5]: a = np.ones((3,4),dtype = float)
In [6]: a
Out[6]:
array([[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]])
In [7]: np.eye(4)
Out[7]:
array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]])
3/8
Creating Matrices with Reshape
In [9]: c = np.arange(6)
In [10]: c
Out[10]: array([0, 1, 2, 3, 4, 5])
In [11]: c = np.reshape(c,(2,3))
In [12]: c
Out[12]:
array([[0, 1, 2], [3, 4, 5]])
4/8
Indexing Multidimensional Arrays
In [14]: b
Out[14]:
array([[1., 4., 5.], [9., 7., 4.]])
In [15]: b[0][2]
Out[15]: 5.0
In [16]: b[0,2]
Out[16]: 5.0
5/8
Matrix Operations
In [17]: b
Out[17]:
array([[1., 4., 5.], [9., 7., 4.]])
In [18]: 2*b
Out[18]:
array([[ 2., 8., 10.], [18., 14., 8.]])
In [19]: b/4
Out[19]:
array([[0.25, 1. , 1.25], [2.25, 1.75, 1. ]])
In [20]: b**2
Out[20]:
array([[ 1., 16., 25.], [81., 49., 16.]])
In [21]: b-2
Out[21]:
array([[-1., 2., 3.], [ 7., 5., 2.]])
In [22]: np.sin(b)
Out[22]: array([[ 0.84147098, -0.7568025 , -0.95892427], [
0.41211849, 0.6569866 , -0.7568025 ]])
6/8
Element-wise Multiplication of Two Arrays
In [24]: b
Out[24]:
array([[1., 4., 5.], [9., 7., 4.]])
In [25]: c
Out[25]:
array([[0, 1, 2], [3, 4, 5]])
In [26]: b*c
Out[26]:
array([[ 0., 4., 10.], [27., 28., 20.]])
7/8
Matrix Multiplication (Linear Algebra)
In [28]: d = np.array([[4,2],[9,8],[-3,6]])
In [29]: d
Out[29]:
array([[ 4, 2], [ 9, 8], [-3, 6]])
In [30]: b
Out[30]:
array([[1., 4., 5.], [9., 7., 4.]])
In [31]: np.dot(b,d)
Out[31]:
array([[25., 64.], [87., 98.]])
8/8
Lecture 10
Dictionaries in Python Programming
M. Asif Farooq
1/6
Dictionaries
List is collection of objects indexed in order sequence.
Dictionary is also a collection of objects but indexed with strings or
numbers or even with tuples.
Dictionaries are a part of core Python similar to List.
Dictionaries are written in curly braces.
2/6
Examples
In [33]: room = "Emma":309, "Jake":582
In [34]: room["Jake"]
Out[34]: 582
In [35]: room["Emma"]
Out[35]: 309
3/6
Examples (Cont. )
In [33]: room = "Emma":309, "Jake":582
In [34]: room["Jake"]
Out[34]: 582
In [35]: room["Emma"]
Out[35]: 309
In [36]: weird = "tank":52, 846:"horse", ’bones’: [23, ’fox’, ’grass’],
’phrase’:’I am here’
In [37]: weird["tank"]
Out[37]: 52
In [38]: weird[846]
Out[38]: ’horse’
In [39]: weird["bones"]
Out[39]: [23, ’fox’, ’grass’] 4/6
Building Dictionaries
In [43]: d = {}
In [44]: d["last name"] = "Farooq"
In [45]: d["first name"] = "Muhammad Asif"
In [46]: d["subject"] = "Mathematics"
In [47]: d
Out[47]:
{’last name’: ’Farooq’, ’first name’: ’Muhammad Asif’, ’subject’:
’Mathematics’}
In [48]: d.keys()
Out[48]: dict_keys([’last name’, ’first name’, ’subject’])
In [49]: d.values()
Out[49]: dict_values([’Farooq’, ’Muhammad Asif’, ’Mathematics’])
5/6
Dictionaries from Tuples
In [51]: g = [("Melissa", "Canada"), ("Jeana", "China")]
In [52]: gd = dict(g)
In [53]: gd
Out[53]: {’Melissa’: ’Canada’, ’Jeana’: ’China’}
In [54]: gd[’Jeana’]
Out[54]: ’China’
6/6
Lecture 11
Conditionals and Loops:
if-Statements
M. Asif Farooq
1/5
Conditional Statements
Conditional statements allow computer program to take different
actions based on whether some conditions are true or false.
2/5
if-elif-else Statement: Example
Write the following program in Python script.
a = 5.0
b = 0.0
c = 8.0
d = b*b - 4*a*c
if d >= 0.0:
print("Solutions are real")
elif b == 0.0:
print("Solutions are imaginary")
else:
print("Solutions")
print("finished")
3/5
if-else Statement
Write the following program in Python script.
a=4
if a % 2 == 0:
print (" The number is even integer")
else:
print("The number is odd")
4/5
if-Statement
Write the following program in Python script.
a = -1
if a < 0:
a = -a
print(a)
5/5
Lecture 11
Plotting in Python
M. Asif Farooq
1 / 10
Outline
Plotting is done in Python by matplotlib.
Use "import matplotlib.pyplot as plt"
create the (x, y) data arrays
Display the plot in figure window using show function
2 / 10
Plotting
In [1]: import numpy as np
In [2]: import matplotlib.pyplot as plt
In [5]: plt.plot([1, 2, 3, 4, 5, 6, 6, 7])
Out[5]: [<matplotlib.lines.Line2D at 0x2ba43062c10>]
In [10]: plt.show()
3 / 10
Plot
import numpy as np
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4, 5, 6, 6, 7])
plt.show()
4 / 10
Plot
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 4.*np.pi, 33)
y = np.sin(x)
plt.plot(x, y)
plt.show()
5 / 10
Plot
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 4.*np.pi, 129)
y = np.sin(x)
plt.plot(x, y)
plt.show()
6 / 10
Plot: Title
import matplotlib.pyplot as plt
x_coord = [0, 1, 2, 3, 4]
y_coord = [0, 3, 1, 5, 2]
plt.plot(x_coord, y_coord)
plt.title(’Sample Data’)
plt.show()
main()
7 / 10
Plot: Label
import matplotlib.pyplot as plt
xcoord = [0, 1, 2, 3, 4]
ycoord = [0, 3, 1, 5, 2]
plt.plot(xcoord, ycoord)
plt.title(’Sample Data’)
plt.xlabel(’This is x-axis’)
plt.ylabel(’This is y-axis’)
plt.show()
8 / 10
Plot:Customizing x and y-axis
import matplotlib.pyplot as plt
xcoord = [0, 1, 2, 3, 4]
ycoord = [0, 3, 1, 5, 2]
plt.plot(xcoord, ycoord)
plt.title(’Sample Data’)
plt.xlabel(’This is x-axis’)
plt.ylabel(’This is y-axis’)
plt.xlim(xmin = -1, xmax = 10)
plt.ylim(ymin = -1, ymax = 6)
plt.grid(True)
plt.show()
9 / 10
Plotting
import matplotlib.pyplot as plt
x_coord = [0, 1, 2, 3, 4]
y_coord = [0, 3, 1, 5, 2]
plt.plot(x_coord, y_coord)
plt.title(’Sales’)
plt.xlabel(’Year’)
plt.ylabel(’Sales’)
plt.xticks([0, 1, 2, 3, 4], [’2016’, ’2017’, ’2018’, ’2019’, ’2020’])
plt.yticks([0, 1, 2, 3, 4], [’om’, ’1m’, ’2m’, ’3m’, ’4m’])
plt.grid(True)
plt.show()
10 / 10
Lecture 12
Conditionals and Loops:
Logical Operators
M. Asif Farooq
1/4
Logical Operator
The logical operator tells a relation between two arrays.
2/4
Operators and Functions
operator function
< less than
≤ less than or equal to
> greater than
≥ greater than or equal to
== equal
!= Not equal
and both must be true
or one or both must be true
not reverses the truth value
Table: Logical operator
3/4
Examples
In [1]: a = 4
In [2]: b = 7
m
In [3]: a!= 5
Out[3]: True
In [4]: a > 2 and b < 20
Out[4]: True
In [5]: a > 2 and b >10
Out[5]: False
In [6]: a > 2 or b >10
Out[6]: True
In [7]: not a >2
Out[7]: False
4/4
Lecture 13
Conditionals and Loops:
for Loops
M. Asif Farooq
1/6
Logical Operator
In computer programming a loop in statement or block of
statements that is executed repeatedly.
Python has two kinds of loops, a for and while loops.
2/6
for loops
for dogname in ["Molly", "’Max", "Buster"]:
print(dogname)
3/6
Examples
s=0
for i in range(1,100,2):
s=s+i
print(s)
4/6
Iterating over sequence
a = ’There are places’
for letter in a:
print(letter)
5/6
Examples
a = ’There are places I remember all my life’
i=0
for letter in a:
if i % 3 == 0:
print(letter, end = ”)
i+= 1
6/6
Lecture 14
Conditionals and Loops:
while Loops
M. Asif Farooq
1/5
while Loops
If the condition remains correct then we use while loops
2/5
Example: Fibonacci Numbers Less Than 1000
x, y = 0,1
while x < 1000:
print(x)
x, y = y, x + y
3/5
Time Calculations in Loops and Arrays
import numpy as np
import time
a = np.linspace(0,32,10000000)
print(a)
startTime =time.process_time()
for i in range (len(a)):
a[i] = a[i]*a[i]
endTime = time.process_time()
print(a)
print(’Run Time = Seconds’.format(endTime-startTime))
27 seconds
4/5
Time Calculations in Loops and Arrays
import numpy as np
import time
a = np.linspace(0,32,10000000)
print(a)
startTime =time.process_time()
a = a*a
endTime = time.process_time()
print(a)
print(’Run Time = Seconds’.format(endTime-startTime))
0.06 seconds
5/5