01 02 04 NITK Python Tutorial
01 02 04 NITK Python Tutorial
01 02 04 NITK Python Tutorial
html
Outline
1. Numpy Library
2. Basics of python
3. Functions
4. Control Statement
5. Materics
6. Ploting
7. Scipy Library
In [ ]:
1 of 1 27-10-2020, 08:32
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
Introduction of NumPy
NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting of multidimensional
array objects and a collection of routines for processing of array.
Numeric, the ancestor of NumPy, was developed by Jim Hugunin. Another package Numarray was also
developed, having some additional functionalities.
In 2005, Travis Oliphant created NumPy package by incorporating the features of Numarray into Numeric
package. There are many contributors to this open source project.
1 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
The Basics
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually
numbers), all of the same type, indexed by a tuple of positive integers.
In NumPy dimensions are called axes. The number of axes is rank.
For example, the coordinates of a point in 3D space [1, 2, 1] is an array of rank 1, because it has one
axis. That axis has a length of 3.
In the example given below, the array has rank 2 (it is 2-dimensional). The first dimension (axis) has a
length of 2, the second dimension has a length of 3.
NumPy’s array class is called ndarray. It is also known by the alias array. Note that numpy.array is not the
same as the Standard Python Library class array.array, which only handles one-dimensional arrays and
offers less functionality.
The more important attributes of an ndarray object are:
1. ndarray.ndim:
The number of axes (dimensions) of the array. In the Python world, the number of dimensions is
referred to as rank.
2. ndarray.shape:
The dimensions of the array. This is a tuple of integers indicating the size of the array in each
dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape
tuple is therefore the rank, or number of dimensions, ndim.
3. ndarray.size:
The total number of elements of the array. This is equal to the product of the elements of shape.
4. ndarray.dtype: An object describing the type of the elements in the array. One can create or specify
dtype’s using standard Python types. Additionally NumPy provides types of its own. numpy.int32,
numpy.int16, and numpy.float64 are some examples.
Python list ( [ ] )
1. A list is a collection of data elements arranged sequentially.
2. They are mutable in nature, and data can inserted, removed and appended.
3. Lists are enclosed by a pair of squared brackets '[]'
4. Lists in Python are heterogeneous. A list can contain any different type of data.
5. Lists are especially good for keeping track of things that change in the course of the program
execution.
2 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
Python tuples ( ( ) )
Similar to lists, tuples are sequences of arbitrary items.
2. Tuples can't be modified using add, delete, or changing of items once the tuple is created. A tuple is
thus a constant list type.
3. A tuple can be created using a pair of parenthesis ().
4. Notice that it is different from how a list can be created by saying "list()"
Function numpy.arange()
1. It is one of the array creation routines based on numerical ranges
2. It creates an instance of ndarray with evenly spaced values and returns the reference to it.
3. You can define the interval of the values contained in an array, space between them, and their type
with four parameters of arange():
numpy.arange(start, stop, step, dtype=None)
Illustrative Examples
In [26]: import numpy as np
a = np.arange(4)
a
In [86]: a = np.arange(3.0) ##
a
3 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
For example, you can create an array from a regular Python list or tuple using the array function. The type
of the resulting array is deduced from the type of the elements in the sequences.
A frequent error consists in calling array with multiple numeric arguments, rather than providing a
single list of numbers as an argument.
WRONG
RIGHT
Printing Arrays
When you print an array, NumPy displays it in a similar way to nested lists, but with the following layout:
One-dimensional arrays are then printed as rows, bidimensionals as matrices and tridimensionals
as lists of matrices.
[2 3 4 6]
2D Numpy Array
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
4 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
In [46]: #Example 2
# Create a 2D Numpy array list of list
import numpy as np
X2D = np.array([[11 ,12,13,11], [21, 22, 23, 24], [31,32,33,34]])
print('2D Numpy Array')
print(X2D)
print("Shape of 2D Array")
print(X2D.shape)
2D Numpy Array
[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
Shape of 2D Array
(3, 4)
Number of Rows : 3
Number of Rows : 3
Number of Columns : 4
Number of Columns : 4
5 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
Complete example
In [52]: import numpy as np
a1 = np.arange(15) ##
print ("a1 = ",a1)
dim1=a1.ndim
shape1=a1.shape
size1=a1.itemsize
datatype1=a1.dtype.name
print ("Number of axes (dimensions) of the array = ", dim1)
print ("Dimension of the array = ", shape1)
print ("Total number of elements of the array = ", size1)
print ("Type of the elements in the array = ", datatype1)
a1 = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
Number of axes (dimensions) of the array = 1
Dimension of the array = (15,)
Total number of elements of the array = 4
Type of the elements in the array = int32
Function reshape()
Using the reshape() function, we can specify the row x column shape that we are seeking.
The Convolution2D layers in Keras however, are designed to work with 3 dimensions per example.
They have 4-dimensional inputs and outputs. This covers colour images (nb_samples,
nb_channels, width, height), but more importantly, it covers deeper layers of the network, where
each example has become a set of feature maps i.e. (nb_samples, nb_features, width, height).
For example :
mnist.load_data() supplies the MNIST digits with structure (nb_samples, 28, 28) i.e. with 2 dimensions per
example representing a greyscale image 28x28.
6 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
[ 0 1 2 3 4 5 6 7 8 9 10 11]
Shape of 1D Array
(12,)
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]]
Shape of 2D Array
(2, 6)
[[ 0 1]
[ 2 3]
[ 4 5]
[ 6 7]
[ 8 9]
[10 11]]
Shape of 2D Array
(6, 2)
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
Shape of 2D Array
(4, 3)
7 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Shape of 2D Array
(3, 4)
[[ 0]
[ 1]
[ 2]
[ 3]
[ 4]
[ 5]
[ 6]
[ 7]
[ 8]
[ 9]
[10]
[11]]
Shape of 2D Array
(12, 1)
Notice how all of the shapes have to account for the number of elements in the tensor. In our example this
is:
rows * columns = 12 elements
We can use the intuitive words rows and columns when we are dealing with a rank 2 tensor. The
underlying logic is the same for higher dimensional tenors even though we may not be able to use the
intuition of rows and columns in higher dimensional spaces.
8 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
In [27]: #Example 1:
## reshape- it genearte 3D matrix
c = np.arange(24).reshape(2,3,4) # 3D array
print(c)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
Axis 0 size : 2
Axis 1 size : 3
Axis 2 size : 4
(2, 3, 4)
In [28]: # Example 2:
c = np.arange(27).reshape(3,3,3) # 3D array
print(c)
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]]
Axis 0 size : 3
Axis 1 size : 3
Axis 2 size : 3
Shape of 3D Array
(3, 3, 3)
9 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
In [24]: # Example 3:
# reshape function
a = np.arange(15).reshape(3, 5) ## reshape- it genearte matrix
of 3 rows and 5 column
print ("a = ",a)
dim=a.ndim
shape=a.shape
size=a.itemsize
datatype=a.dtype.name
print ("Number of axes (dimensions) of the array = ", dim)
print ("Dimension of the array = ", shape)
print ("Total number of elements of the array = ", size)
print ("Type of the elements in the array = ", datatype)
a = [[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Number of axes (dimensions) of the array = 2
Dimension of the array = (3, 5)
Total number of elements of the array = 4
Type of the elements in the array = int32
10 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
In [25]: # Example 4:
## reshape- it genearte matrix of 2 rows and 3 columns
c1 = np.arange(12).reshape(3,4) # 2D array
print(c1)
c = c1.reshape(3,2,2,1) # 4D array
print("Array after reshaping")
print(c)
print("Shape of Array after reshaping")
print(c.shape)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
Array after reshaping
[[[[ 0]
[ 1]]
[[ 2]
[ 3]]]
[[[ 4]
[ 5]]
[[ 6]
[ 7]]]
[[[ 8]
[ 9]]
[[10]
[11]]]]
Shape of Array after reshaping
(3, 2, 2, 1)
We can reshape an 8 elements 1D array into 4 elements in 2 rows 2D array but we cannot reshape it into
a 3 elements 3 rows 2D array as that would require 3x3 = 9 elements.
11 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
In [37]: print(np.arange(10000).reshape(100,100))
[[ 0 1 2 ... 97 98 99]
[ 100 101 102 ... 197 198 199]
[ 200 201 202 ... 297 298 299]
...
[9700 9701 9702 ... 9797 9798 9799]
[9800 9801 9802 ... 9897 9898 9899]
[9900 9901 9902 ... 9997 9998 9999]]
To disable this behaviour and force NumPy to print the entire array, you can change the printing options using
set_printoptions. np.set_printoptions(threshold='nan')
ndarry.itemsize
This array attribute returns the length of each element of array in bytes
[ 2 4 6 8 10]
1
In [31]: #Example 2
# dtype of array is int16 (2 bytes)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.int16)
print(x)
print(x.itemsize)
[ 2 4 6 8 10]
2
In [32]: #Example 3
# dtype of array is int32 (4 bytes)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.int32)
print(x)
print(x.itemsize)
[ 2 4 6 8 10]
4
12 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
In [33]: #Example 4
# dtype of array is float32 (4 bytes)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.float32)
print(x)
print(x.itemsize)
[ 2. 4. 6. 8. 10.]
4
In [34]: #Example 5
# dtype of array is float32 (8 bytes)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.float64)
print(x)
print(x.itemsize)
[ 2. 4. 6. 8. 10.]
8
In [37]: #Example 6
# dtype of array is complex64 (8 bytes)
import numpy as np
x = np.array([2,4,6,8,10], dtype = np.complex128)
print(x)
print(x.itemsize)
[[[11 12 13 11]
[21 22 23 24]
[31 32 33 34]]
[[ 1 1 1 1]
[ 2 2 2 2]
[ 3 3 3 3]]]
Axis 0 size : 2
Axis 1 size : 3
Axis 2 size : 4
13 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
Out[6]: array([[1.5, 2. , 3. ],
[4. , 5. , 6. ]])
The type of the array can also be explicitly specified at creation time:
To create sequences of numbers, NumPy provides a function analogous to range that returns arrays
instead of lists.
When arange is used with floating point arguments, it is generally not possible to predict the number of
elements obtained, due to the finite floating point precision. For this reason, it is usually better to use the
function linspace that receives as an argument the number of elements that we want, instead of the step:
14 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
15 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
a= [[0 1]
[2 3]]
b= [[4 5]
[6 7]]
In [63]: np.vstack((a,b))
In [64]: np.hstack((a,b))
16 of 17 29-10-2020, 12:58
1_Numpy file:///C:/Users/Shyam/AppData/Local/Temp/1_Numpy-1.html
In [17]: np.hsplit(b,(3,4)) # Split a after the third and the fourth column
In [ ]:
17 of 17 29-10-2020, 12:58
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
Python Basics
In [1]: # Simple program #(Select shell + ctrl+/) for commenting whole
shell
Hello World
Indentation
Python does not use braces({}) to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented
the same amount.
In [3]: if True:
print ("Answer")
print () # Prints a blank line
print ("True")
else:
print ("Answer")
print ("False")
Answer
True
Strings in Python
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the
same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all the following are legal
1 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
print (word)
print()
print (sentence)
print()
print (paragraph)
word
This is a sentence.
This is a paragraph. It is
made up of multiple lines and sentences.
Comments in Python
A hash sign (#) that is not inside a string literal is the beginning of a comment. All characters after the #,
up to the end of the physical line, are part of the comment and the Python interpreter ignores them. There
are no multiline comments. One has to comment each line.
Hello, Python!
Python variables
Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to
variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable.
print (counter)
print (miles)
print (name)
100
1000.0
John
2 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
In [9]: a = b = c = 1
d, e, f = 1, 2, "john"
1 1 1
1 2 john
Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to them.
In [10]: var1 = 1
var2 = 10
print(var1,var2)
1 10
3 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
In [11]: var_int = 10
var_float = 10.5
var_complex = 10+5j
print(var_int, type(var_int))
print(var_float, type(var_float))
print(var_complex, type(var_complex))
10 <class 'int'>
10.5 <class 'float'>
(10+5j) <class 'complex'>
Python lists
A list contains items separated by commas and enclosed within square brackets ([]).
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0
in the beginning of the list and working their way to end -1.
The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
#list.extend(tinylist)
#print(list)
list.append(zeros)
print(list)
4 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
Python Tuples
A tuple is another sequence data type that is similar to the list.
A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed
within parenthesis.
The main difference between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements
and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples
can be thought of as read-only lists.
The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.
Similar case is possible with lists
Python Dictionary
Python's dictionaries are kind of hash-table type. A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([ ]).
5 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
In [36]: dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
This is one
This is two
{'name': 'john', 'code': 6734, 'dept': 'sales'}
dict_keys(['name', 'code', 'dept'])
dict_values(['john', 6734, 'sales'])
Datatype conversion
int(x [,base]) : Converts x to an integer. The base specifies the base if x is a string.
111
73
15
2
<class 'str'>
<class 'float'>
<class 'int'>
<class 'int'>
<class 'int'>
In [ ]:
6 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
Python Operators
Python language supports the following types of operators
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
7 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
a = 0011 1100
b = 0000 1101
~a = 1100 0011
Python's built-in function bin() can be used to obtain binary representation of an integer number.
8 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
9 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
Basic Operations
Arithmetic operators on arrays apply elementwise. A new array is created and filled with the result.
[20 30 40 50]
[0 1 2 3]
In [44]: # Addition
c = a+b
c
In [45]: # subtraction
c = a-b
c
In [4]: # power of 3
b**3
In [6]: a<35
Unlike in many matrix languages, the product operator * operates elementwise in NumPy arrays. The
matrix product can be performed using the dot function or method:
10 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
Some operations, such as += and *=, act in place to modify an existing array rather than create a new one
In [17]: b += a
b
When operating with arrays of different types, the type of the resulting array corresponds to the more
general or precise one (a behavior known as upcasting).
Out[21]: 'float64'
In [22]: c = a+b
c
In [23]: c.dtype.name
Out[23]: 'float64'
In [24]: d = np.exp(c*1j)
d
Many unary operations, such as computing the sum of all the elements in the array, are implemented as
methods of the ndarray class.
11 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
In [25]: a = np.random.random((2,3))
a
In [26]: a.sum()
Out[26]: 4.952880791168187
In [27]: a.min()
Out[27]: 0.7364701794052217
In [28]: a.max()
Out[28]: 0.9270061402955219
By default, these operations apply to the array as though it were a list of numbers, regardless of its shape.
However, by specifying the axis parameter you can apply an operation along the specified axis of an
array:
In [29]: b = np.arange(12).reshape(3,4)
b
12 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
Universal Functions
NumPy provides familiar mathematical functions such as sin, cos, and exp. In NumPy, these are called
“universal functions”(ufunc). Within NumPy, these functions operate elementwise on an array, producing
an array as output.
Often, the elements of an array are originally unknown, but its size is known. Hence, NumPy offers
several functions to create arrays with initial placeholder content. These minimize the necessity of
growing arrays, an expensive operation.
The function zeros creates an array full of zeros, the function ones creates an array full of ones,
and the function empty creates an array whose initial content is random and depends on the state
of the memory. By default, the dtype of the created array is float64.
In [38]: np.zeros(5)
In [39]: np.ones(5)
In [40]: np.exp(B)
In [41]: np.sqrt(B)
13 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
Out[48]: array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729], dtype=in
t32)
In [49]: a[3]
Out[49]: 27
Out[53]: array([ 729, 512, 343, 216, 125, -1000, 27, -1000,
1,
-1000], dtype=int32)
Multidimensional arrays can have one index per axis. These indices are given in a tuple separated by
commas:
Out[55]: 23
14 of 15 29-10-2020, 12:59
2_Basics file:///C:/Users/Shyam/AppData/Local/Temp/2_Basics-1.html
In [39]: x = 3;
y = "Hello"
print( x, y)
z= x
print(id(z))
print(id(x))
print (id(y))
print(x is z)
print(x is y)
3 Hello
94394468535584
94394468535584
140003051108256
True
False
In [ ]:
In [ ]:
15 of 15 29-10-2020, 12:59
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html
Defining Functions
Defining functions use the def command.
Functions can have arguments and return values
Invoked by the name of the function
Function Call
In [6]: happy()
def hbd(name):
print ("Happy Birthday to ", name)
return
Function calling
In [11]: z = 3;
w = square(z);
print("3x3 = ", w);
3x3 = 9
3 squared twice 81
In expression 14
1 of 3 30-07-2020, 09:16
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html
hbd(name)
Function Parameters
In [14]: import numpy as np
def addinterest(balance,rate):
balance = balance + np.multiply(balance , rate)
print(balance)
# print(newbalance)
return balance
#print(amount is addinterest)
print(id(addinterest))
id(amount)
[105. 210.]
Amount = [100, 200]
2222603905928
Out[14]: 2222608615368
Arrays
The function can change the value of the arguments
2 of 3 30-07-2020, 09:16
3_Functions file:///C:/Users/Shyam/AppData/Local/Temp/3_Functions.html
print(id(bal_list))
return
addinterests(amounts,rate)
print(amounts)
print(id(amounts))
print(id(addinterests))
140036883512264
[1050.0, 2000, 3000, 5000]
140036883512264
140037146633488
In [80]: x=[1,2,3,4,5,6]
x1=np.zeros(5)
np.append(x,np.append(x1,x))
#x1
Out[80]: array([ 1., 2., 3., 4., 5., 6., 0., 0., 0., 0., 0., 1., 2.,
3., 4., 5., 6.])
Mean finding
In [16]: import numpy as np
def mean(x):
b=np.sum(x)
y=b/len(x)
print(y)
return y
Calling function
In [17]: a=np.arange(6)
z=mean(a)
2.5
In [ ]:
3 of 3 30-07-2020, 09:16
4_Control Statements file:///C:/Users/Shyam/AppData/Local/Temp/4_Control Statements.html
Branch Statements
Conditional execution : if
Two way decision : if-else
Multi way decision : if-elif-if
Loop statements
Range based : for
Decision based : while
Conditional Execution
In [3]: # Example
temp = int(input("What is the temperature ? "));
if(temp > 35):
print(" Too hot !!")
import numpy as np
def quad_solv(a,b,c):
# This function determines the roots of a
# quadratic equation if they are real.
discrim = b*b - 4*a*c;
if(discrim >= 0):
sqrtdiscr = np.sqrt(discrim);
root1 = (-b + sqrtdiscr)/(2*a);
root2 = (-b - sqrtdiscr)/(2*a);
print ("Roots = ", root1, ",",root2);
else:
print ("No real roots" )
return;
In [ ]: ## Function Calling
a = int(input(" Enter the value of a="));
b = int(input(" Enter the value of b="));
c= int(input(" Enter the value of c="));
quad_solv(a,b,c)
1 of 4 30-07-2020, 09:14
4_Control Statements file:///C:/Users/Shyam/AppData/Local/Temp/4_Control Statements.html
In [4]: print(max3(10,20,30))
30
-10
For Loops
Most common loop is the "for" loop
Examples
0
1
2
3
4
Note that the "i" ranges from 0 to 4 The last value is never included
2 of 4 30-07-2020, 09:14
4_Control Statements file:///C:/Users/Shyam/AppData/Local/Temp/4_Control Statements.html
3
5
7
9
1.5
2.0
2.5
3.0
3.5
4.0
4.5
While Loop
This constructs repeatedly checks a condition and executes till it is true
In [12]: count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
3 of 4 30-07-2020, 09:14
4_Control Statements file:///C:/Users/Shyam/AppData/Local/Temp/4_Control Statements.html
In [13]: count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
else:
print ("Loop Over")
In [ ]:
4 of 4 30-07-2020, 09:14
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html
[0 1 2]
[3 4 5]
[[1 2 3]
[4 5 6]
[7 8 9]]
[[10 20 30]
[40 50 60]
[70 80 90]]
Example
In Python, we can implement a matrix as a nested list (list inside a list). We can treat each element as a row of the matrix.
For example A = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. First row can be selected as A[0] and the element in first
row, first column can be selected as A[0[0].
We can perform matrix addition in various ways in Python. Here are a couple of them.
1 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html
# first matrix
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# second matrix
b = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# In this matrix we will store the sum of above matrices
# we have initialized all the elements of this matrix as zero
sum = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# iterating the matrix
# rows: number of nested lists in the main list
# columns: number of elements in the nested lists
for i in range(len(a)):
for j in range(len(a[0])):
sum[i][j] = a[i][j] + b[i][j]
2 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html
# first matrix
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# second matrix
b = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# In this matrix we will store the sum of above matrices
# we have initialized all the elements of this matrix as zero
sum = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# iterating the matrix
# rows: number of nested lists in the main list
# columns: number of elements in the nested lists
result = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]
for r in result:
print(r)
[[1 2 3]
[4 5 6]
[7 8 9]]
[[10 20 30]
[40 50 60]
[70 80 90]]
3 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html
# first matrix
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# second matrix
b = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# In this matrix we will store the sum of above matrices
# we have initialized all the elements of this matrix as zero
sub = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# iterating the matrix
# rows: number of nested lists in the main list
# columns: number of elements in the nested lists
for i in range(len(a)):
for j in range(len(a[0])):
sub[i][j] = b[i][j] - a[i][j]
# first matrix
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# second matrix
b = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# In this matrix we will store the sum of above matrices
# we have initialized all the elements of this matrix as zero
sum = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
# iterating the matrix
# rows: number of nested lists in the main list
# columns: number of elements in the nested lists
result = [[b[i][j] - a[i][j] for j in range(len(a[0]))] for i in range(len(a))]
for r in result:
print(r)
4 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html
[[1 2 3]
[4 5 6]
[7 8 9]]
[[10 20 30]
[40 50 60]
[70 80 90]]
If A is a n x m matrix and B is a m x l matrix then, AB is defined and has the dimension n x l (but BA is not defined). Here are a
couple of ways to implement matrix multiplication in Python.
# first matrix
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# second matrix
B = [[10, 20, 30],
[40, 50, 60],
[70, 80, 90]]
# result is 3x4
mul_result = [[0,0,0],
[0,0,0],
[0,0,0]]
for r in mul_result:
print(r)
5 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html
This technique is simple but computationally expensive as we increase the order of the matrix.
For larger matrix operations we recommend optimized software packages like NumPy which is several (in the order of 1000)
times faster than the above code.
# result is 3x4
result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in
X]
for r in result:
print(r)
Matrix Power
In [2]: import numpy as np
import matplotlib.pyplot as pyplot
X = np.matrix('1 2 3; 4 5 6; 7 8 9')
print(X)
np.power(X, 2)
[[1 2 3]
[4 5 6]
[7 8 9]]
6 of 7 30-07-2020, 09:18
5_Matrices file:///C:/Users/Shyam/AppData/Local/Temp/5_Matrices.html
[[ 2 4 6]
[ 4 8 6]
[ 2 8 10]]
2
Matrix Inverse
In [20]: import numpy as np
import matplotlib.pyplot as pyplot
a = np.matrix('1 2 3; 4 5 6; 7 8 0')
print(a)
ainv = np.linalg.inv(a)
print (ainv)
[[1 2 3]
[4 5 6]
[7 8 0]]
[[-1.77777778 0.88888889 -0.11111111]
[ 1.55555556 -0.77777778 0.22222222]
[-0.11111111 0.22222222 -0.11111111]]
In [ ]:
7 of 7 30-07-2020, 09:18