Python_1_merged
Python_1_merged
M. Asif Farooq
1 / 18
What is Python language?
2 / 18
Installing Python
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 [25]: (2+3j)/(-4+9j)
Out[25]: (0.1958762886597938-0.3092783505154639j)
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
11 / 18
Note About Printing
12 / 18
Python Module
13 / 18
Python Modules and Functions
In [36]: import numpy
In [37]: numpy.sin(0.5)
Out[37]: 0.479425538604203
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
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
2 / 12
What is a String?
3 / 12
Examples
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
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
8 / 12
Substring: Examples
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
12 / 12
Lecture 5
Data Structures in Python Programming:
Lists
M. Asif Farooq
1/9
Lists
2/9
Lists: Examples
In [8]: a = [0, 1,1, 2, 3, 4]
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 [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 [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 [25]: a + b
Out[25]: [’vegetable’, ’fruits’, 4, 7, 5, ’boys and girls’]
5/9
Slicing Lists: Examples
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 [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
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
5/8
Examples: Converting Lists or Strings into Tuples
In [1]: tuple([’fruits’, ’vegetables’])
Out[1]: (’fruits’, ’vegetables’)
In [3]: tuple("spam")
Out[3]: (’s’, ’p’, ’a’, ’m’)
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
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
4/4
Lecture 8
NumPy Arrays
M. Asif Farooq
1/6
Creating Arrays in One Dimension
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
4/6
Examples
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
2/8
Creating Matrices
In [2]: import numpy as np
In [4]: b
Out[4]: array([[1., 4., 5.], [9., 7., 4.]])
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
2/6
Examples
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 [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 [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 [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
2/5
if-elif-else Statement: Example
3/5
if-else Statement
a=4
if a % 2 == 0:
print (" The number is even integer")
else:
print("The number is odd")
4/5
if-Statement
5/5
Lecture 11
Plotting in Python
M. Asif Farooq
1 / 10
Outline
2 / 10
Plotting
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
7 / 10
Plot: Label
8 / 10
Plot:Customizing x and y-axis
9 / 10
Plotting
10 / 10
Lecture 12
Conditionals and Loops:
Logical Operators
M. Asif Farooq
1/4
Logical Operator
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
M. Asif Farooq
1/6
Logical Operator
2/6
for loops
3/6
Examples
s=0
for i in range(1,100,2):
s=s+i
print(s)
4/6
Iterating over sequence
5/6
Examples
6/6
Lecture 14
Conditionals and Loops:
while Loops
M. Asif Farooq
1/5
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