Basics of Python and Numpy
Basics of Python and Numpy
Basics of Python and Numpy
and
Numpy
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)
print(“a={:f}".format(123.4567898)) #a=123.456790
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:])
The plus (+) sign is the list concatenation operator, and the
asterisk (*) is the repetition operator.
The main differences 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.
A dictionary key can be almost any Python type, but are usually
numbers or strings.
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 operator. a + b = 31
- Subtraction Subtracts right hand operand from left hand a – b = -11
operand.
* Multiplication Multiplies values on either side of the a * b = 210
operator
/ Division Divides left hand operand by right hand b / a = 2.1
operand
% Modulus Divides left hand operand by right hand b % a = 1
operand and returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to
operators the power 21
// Floor Division - The division of operands 9//2 = 4 and
where the result is the quotient in which the 9.0//2.0 = 4.0
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 copies a bit to the result (a & b) (means 0000 1100)
if it exists in both operands
| It copies a bit if it exists in either (a | b) = 61 (means 0011
operand. 1101)
^ It copies the bit if it is set in one (a ^ b) = 49 (means 0011
operand but not both. 0001)
~ It is unary and has the effect of (~a ) = -61 (means 1100
'flipping' bits. 0011 in 2's complement
form due to a signed
binary number.
<< The left operands value is moved a << = 2 (means 1111
left by the number of bits 0000)
specified by the right operand.
>> The left operands value is moved a >> = 2 (means 0000
right by the number of bits 1111)
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 dimension.
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
b=np.array([[11,5,14],[2,5,1]]) [
[11, 5, 14],
[2, 5, 1]
]
np.sort(b) # array([[ 5, 11, 14],
[ 1, 2, 5]])
np.sort(b,axis=1) # array([[ 5, 11, 14],
[ 1, 2, 5]])
np.sort(b,axis=0) # array([[ 2, 5, 1],
[ 11, 5, 14]])
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.