Basics of Python and Numpy (2)
Basics of Python and Numpy (2)
and
Numpy
Disclaimer
⮚ Content of this presentation is not original and
it has been prepared from various sources for
teaching purpose.
Introduction
⮚ Python is an interpreted, interactive, object-
oriented, and high-level programming
language.
⮚ Python was developed by Guido van Rossum in
1991.
⮚ Python Features
⮚ Easy-to-learn
⮚ Easy-to-read
⮚ A broad standard library
⮚ Databases
⮚ GUI Programming
Introduction
⮚ Python Comments: #
⮚ a=5
⮚ b=2
⮚ print(a) #5
⮚ print(a, b) #52
⮚ print(a) #5
print(b) #2
⮚ print(“Value of a =“, a)
⮚ Numbers
⮚ String
⮚ List
⮚ Tuple
⮚ Dictionary
Standard Data Types
⮚ Numbers
⮚ int
⮚ All integers in Python3 are represented as long integers.
Hence there is no separate number type as long.
⮚ float
⮚ complex
⮚ A complex number consists of an ordered pair of real
floating-point numbers denoted by x + yj, where x and y are
the real numbers and j is the imaginary unit.
Standard Data Types
⮚ Numbers
⮚ Examples
⮚ print (str[-1])
⮚ print (str[-3:-1])
⮚ print (str[-12:])
⮚ a=int(input(“Enter a:”));
⮚ a, b, c=eval(input(“Enter a, b, c:”))
Matrices
⮚ a=[
[1,2,3],
[4,5,6]
]
⮚ Arithmetic Operators
⮚ Assignment Operators
⮚ Logical Operators
⮚ Bitwise Operators
⮚ Membership Operators
⮚ Identity Operators
Basic Operators
⮚ Arithmetic Operators
⮚ Assume variable a holds 10 and variable b holds 21,
then −
Operator Description Example
+ Addition Adds values on either side of the a + b = 31
operator.
- Subtraction Subtracts right hand operand from left a – b = -11
hand operand.
* Multiplies values on either side of the a * b = 210
Multiplication operator
/ Division Divides left hand operand by right b / a = 2.1
hand operand
% Modulus Divides left hand operand by right b%a=1
hand operand and returns remainder
** Exponent Performs exponential (power) a**b =10 to
calculation on operators the power 21
// Floor Division - The division of 9//2 = 4 and
operands where the result is the 9.0//2.0 = 4.0
quotient in which the digits after the
decimal point are removed. But if one
of the operands is negative, the result
is floored, i.e., rounded away from zero
(towards negative infinity):
Basic Operators
⮚ Comparison Operators
⮚ Assume variable a holds 10 and variable b holds 20,
then-
Operator Description Example
== If the values of two operands are (a == b) is not
equal, then the condition becomes true.
true.
!= If values of two operands are not (a!= b) is true.
equal, then condition becomes true.
> If the value of left operand is greater (a > b) is not
than the value of right operand, then true.
condition becomes true.
< If the value of left operand is less (a < b) is true.
than the value of right operand, then
condition becomes true.
>= If the value of left operand is greater (a >= b) is not
than or equal to the value of right true.
operand, then condition becomes
true.
<= If the value of left operand is less (a <= b) is true.
than or equal to the value of right
Basic Operators
⮚ Assignment Operators
⮚ Assume variable a holds 10 and variable b holds 20,
then-
Operat Description Example
or
= Assigns values from right side operands c = a + b assigns
to left side operand value of a + b into
c
+= It adds right operand to the left c += a is equivalent
operand and assign the result to left to c = c + a
operand
-= It subtracts right operand from the left c -= a is equivalent
operand and assign the result to left to c = c - a
operand
*= It multiplies right operand with the left c *= a is equivalent
operand and assign the result to left to c = c * a
operand
/= It divides left operand with the right c /= a is equivalent
operand and assign the result to left to c = c / a
operand
%= It takes modulus using two operands c %= a is
and assign the result to left operand equivalent to c = c
Basic Operators
⮚ Bitwise Operators
⮚ Assume a = 60 = 0011 1100 and b = 13 = 0000
1101, then- Description
Operato Example
r
& Operator copies a bit to the (a & b) (means 0000
result if it exists in both 1100)
operands
| It copies a bit if it exists in (a | b) = 61 (means
either operand. 0011 1101)
^ It copies the bit if it is set in (a ^ b) = 49 (means
one operand but not both. 0011 0001)
~ It is unary and has the effect (~a ) = -61 (means
of 'flipping' bits. 1100 0011 in 2's
complement form due
to a signed binary
number.
<< The left operands value is a << = 2 (means 1111
moved left by the number of 0000)
bits specified by the right
operand.
Basic Operators
⮚ Logical Operators
⮚ Assume a = True (Case Sensitive) and b = False
(Case Sensitive), then-
Output:
1 - Got a true expression value
100
Good bye!
Decision Making
⮚ if else
⮚ if expression:
statement(s)
else:
statement(s)
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
Decision Making
⮚ Nested if
num=int(input("enter number"))
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
Loops
⮚ While Loop
while expression:
statement(s)
count = 0
while count < 9:
print ('The count is:', count)
count = count + 1
Output:
0
1
2
3
4
Loops
⮚ for Loop
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Loops
⮚ for Loop
Output:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Loops
⮚ for Loop
⮚ Iterating by Sequence Index
Output:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Loops
⮚ Break Statement
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Loops
⮚ Continue Statement
Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Loops
⮚ Using else Statement with Loops
• Python supports to have an else statement associated
with a loop statement
numbers=[11,33,55,39,55,75,37,21,23,41,13]
Output:
the list does not contain even number
Numbers - Revisited
⮚ Numbers
⮚ Number Type Conversion
⮚ Type int(x) to convert x to a plain integer.
Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics',
'chemistry', 2000]
Lists - Revisited
⮚ Basic List Operations
1 len(list)
Gives the total length of the list.
2 max(list)
Returns item from the list with max value.
3 min(list)
Returns item from the list with min value.
4 list.copy()
Returns a copy of the list
Lists - Revisited
⮚ List Methods
SN Methods with Description
1 list.append(obj)
Appends object obj to list. Returns None.
2 list.count(obj)
Returns count of how many times obj occurs in list
3 list.index(obj)
Returns the lowest index in list that obj appears
4 list.insert(index, obj)
Inserts object obj into list at offset index
5 list.pop()
Removes and returns last object or obj from list
6 list.remove(obj)
Removes first instance of obj from list
7 list.reverse()
Reverses objects of list in place
8 list.sort()
Sorts objects of list in place
Python Functions
⮚ Defining a Function
Output:
Values inside the function before change: [10, 20, 30]
Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
Python Functions
⮚ Pass by reference vs value
Output:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Python Functions
⮚ Global vs. Local Variables
⮚ Variables that are defined inside a function body
have a local scope, and those defined outside have a
global scope.
Output:
Inside the function local total : 30
Outside the function global total : 0
Python Functions
⮚ Global vs. Local Variables
Output:
Inside the function local total : 30
Outside the function global total : 30
⮚ import numpy as np
⮚ C:\\Python34\scripts>pip3.4 list
Strange - Shape is a settable property and it is a tuple and you can concatenate the
Numpy
⮚ np.array
⮚ Two dimensional array: reshape(), transpose() &
flatten()
Numpy
⮚ np.array
⮚ Two dimensional array: concatenate()
Numpy
⮚ np.array
⮚ Two dimensional array: concatenate()
Numpy
⮚ np.array
⮚ Other ways to create array
Numpy
⮚ np.array
⮚ Array mathematics
Numpy
⮚ np.array
⮚ Array mathematics
Numpy
⮚ np.array
⮚ Array mathematics - Broadcasting
Numpy
⮚ np.array
⮚ Array mathematics - Broadcasting
Numpy
⮚ np.array
⮚ Array mathematics
Numpy
⮚ np.array
⮚ Array mathematics
Numpy
⮚ np.array
⮚ Array iteration
Numpy
⮚ np.array
⮚ Basic array operations
⮚ np.mean(a)
⮚ np.var(a)
⮚ np.std(a)
⮚ np.min(a)
⮚ np.max(a)
⮚ np.argmin(a)
⮚ np.argmax(a)
⮚ np.sort(a) (not in place)
Numpy
⮚ np.array
⮚ Basic array operations
⮚ a=np.array([[1,2],[3,4]]) [
[1, 2],
[3, 4]
]
⮚ np.mean(a) #2.5
⮚ np.mean(a,axis=0) #array([ 2., 3.]) #column wise
⮚ np.mean(a,axis=1) #array([ 1.5, 3.5]) #row wise
⮚ b=np.array([[11,5,14],[2,5,1]]) [
[11, 5, 14],
[2, 5, 1]
]
Numpy
⮚ np.array
⮚ Basic array operations
Numpy
⮚ np.array
⮚ Comparison Operators & Value Testing
Numpy
⮚ np.array
⮚ Comparison Operators & Value Testing
Numpy
⮚ np.array
⮚ Where Function
Numpy
⮚ np.array
⮚ Checking for NaN and Inf
Numpy
⮚ np.array
⮚ Array Item Selection & Manipulation
Numpy
⮚ np.array
⮚ Vector and Matrix Mathematics
Numpy
⮚ np.array
⮚ Vector and Matrix Mathematics
Numpy
⮚ np.array
⮚ Statistics
Numpy
⮚ np.array
⮚ Random Numbers
Numpy
⮚ np.array
⮚ Random Numbers
Saving and Loading Numpy
Array
# Single array saving and loading
x = np.arange(10)
#save
np.save(‘outfile’, x)
#load
x = np.load(‘outfile.npy’)
print(x)
Saving and Loading Numpy
Array
# Multiple array saving and loading
x = np.arange(10)
y = np.random.randint(1, 10, (2, 3))
#save
np.savez(‘outfile’, x, y) # or np.savez(‘outfile’, x = x, y = y)
#load
dict = np.load(‘outfile.npz’)
x = dict[‘arr_0’] # or x = dict[‘x’]
y = dict[‘arr_1’] # or y = dict[‘y’]
print(x, y)
Disclaimer
⮚ Content of this presentation is not original and
it has been prepared from various sources for
teaching purpose.