Basics of Python and Numpy

Download as pdf or txt
Download as pdf or txt
You are on page 1of 98

Basics of Python

and
Numpy

Dr. Priyank Thakkar


Associate Professor
Computer Science and Engineering Department
Institute of Technology
Nirma University
Introduction
 Python is an interpreted, interactive, object-
oriented, and high-level programming language.

 Python Features
 Easy-to-learn
 Easy-to-read
 A broad standard library
 Databases
 GUI Programming
Introduction
 Python Comments: #

 Help in Python: help(topic)


 If no argument is given, the interactive help system
starts on the interpreter console. If the argument is a
string, then the string is looked up as the name of a
module, function, class, method, keyword, or
documentation topic, and a help page is printed on the
console.
Printing in Python
 Syntax: print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

 print("Hello World") #Hello World

 a=5

 b=2

 print(a) #5

 print(a, b) #52

 print(a) #5
print(b) #2

 print(“Value of a =“, a)

 print (“Value of b =“, b)


Printing in Python
 print("a={0}".format(a)) #a=5

 print("a={0} and b={1}".format(a, b)) #a=5 and b=2

 print("a={1} and b={0}".format(a, b)) #a=2 and b=5

 print(“a={} and b={}”.format(a, b)) #a=5 and b=2 #automatic field


numbering

 print("bin={0:b}, oct={0:o}, hex={0:x}".format(12)) #bin=1100, oct=14,


hex=c

 print("bin={0:b}, oct={1:o}, hex={1:x}".format(12,10)) #bin=1100, oct=12,


hex=a

 print("bin={:b}, oct={:o}, hex={:X}".format(12,10,10)) #bin=1100, oct=12,


hex=A
Printing – Padding & Alignment
 print("a={0:d} and b={1:d}".format(a, b)) #a=5 and b=2

 print("a={0:3d} and b={1:5d}".format(a, b)) #a= 5 and b= 2

 print("a={0:>3d} and b={1:>5d}".format(a, b)) #a= 5 and b= 2

 print("a={0:<3d} and b={1:<5d}".format(a, b)) #a=5 and b=2

 print("a={0:03d} and b={1:05d}".format(a, b)) #a=005 and b=00002

 print("a={0:^3d} and b={1:^5d}".format(a, b)) #a= 5 and b= 2

 print(“a={:f}".format(123.4567898)) #a=123.456790

 print("a={:8.3f}".format(123.4567898)) #a= 123.457


Standard Data Types
 Python has five standard data types −

 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.

 Integers in Python 3 are of unlimited size.

 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

int float complex


10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e1-36j
0o70 32.3e18 .876j
-0o470 -90. -.6545+0J
-0x260 -32.54e100 3e1+26J
0x69 70.2E-12 4.53e1-7j
Standard Data Types
 Strings
 Strings in Python are identified as a contiguous set of
characters represented in the quotation marks.

 Python allows for either pairs of single or double quotes.

 Subsets of strings can be taken using the slice operator


([ ] and [:] ) with indexes starting at 0 in the beginning of
the string.

 The plus (+) sign is the string concatenation operator and


the asterisk (*) is the repetition operator.

 Trying to access elements beyond the length of the


string results in an error.
Standard Data Types
 Strings
 str = 'Hello World!'

 print (str) # Prints complete string


 print (str[0]) # Prints first character of the string
 print (str[2:5]) # Prints characters starting from 3rd to 5th
 print (str[2:]) # Prints string starting from 3rd character
 print (str * 2) # Prints string two times
 print (str + "TEST") # Prints concatenated string

 This will produce the following result −


 Hello World!
 H
 llo
 llo World!
 Hello World!Hello World!
 Hello World!TEST
Standard Data Types
 Strings
 str = 'Hello World!'

 print (str[-1])
 print (str[-3:-1])
 print (str[-12:])

 This will produce the following result −


 !
 ld
 Hello World!
Standard Data Types
 Strings
 Python strings cannot be changed — they are immutable.

 Therefore, assigning to an indexed position in the string


results in an error

 I.e. str[0] = ‘J’ results in an error. However, str=“welcome” works.


Standard Data Types
 List
 A list contains items separated by commas and enclosed within
square brackets ([]).

 To some extent, lists are similar to arrays in C. One


difference between them is that all the items belonging to a
list can be of different data type.

 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 from -1 at the end.

 The plus (+) sign is the list concatenation operator, and the
asterisk (*) is the repetition operator.

 Unlike strings, which are immutable, lists are a mutable type,


i.e. it is possible to change their content.

 Trying to access/assign elements beyond the length of the list


results in an error.
Standard Data Types
 List
 list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
 tinylist = [123, 'john']

 print (list) # Prints complete list


 print (list[0]) # Prints first element of the list
 print (list[1:3]) # Prints elements starting from 2nd till 3rd
 print (list[2:]) # Prints elements starting from 3rd element
 print (tinylist * 2) # Prints list two times
 print (list + tinylist) # Prints concatenated lists

 This produce the following result −


 ['abcd', 786, 2.23, 'john', 70.2]
 abcd
 [786, 2.23]
 [2.23, 'john', 70.2]
 [123, 'john', 123, 'john']
 ['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Standard Data Types
 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 parentheses.

 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.

 Tuples can be thought of as read-only lists/immutable lists.


Standard Data Types
 Tuples
 tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
 tinytuple = (123, 'john')

 print (tuple) # Prints complete tuple


 print (tuple[0]) # Prints first element of the tuple
 print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
 print (tuple[2:]) # Prints elements starting from 3rd element
 print (tinytuple * 2) # Prints tuple two times
 print (tuple + tinytuple) # Prints concatenated tuple

 This produce the following result −


 ('abcd', 786, 2.23, 'john', 70.2)
 abcd
 (786, 2.23)
 (2.23, 'john', 70.2)
 (123, 'john', 123, 'john')
 ('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
Standard Data Types
 Tuples
 tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )

 list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]

 tuple[2] = 1000 # Invalid syntax with tuple

 list[2] = 1000 # Valid syntax with list


Standard Data Types
 Dictionary
 Dictionaries consist of key-value pairs.

 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 ([]).

 Dictionaries have no concept of order among elements.

 It is incorrect to say that the elements are "out of order";


they are simply unordered.

 Dictionaries are mutable.


Standard Data Types
 Dictionary
 dict = {}
 dict['one'] = "This is one"
 dict[2] = "This is two"
 tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

 print (dict['one']) # Prints value for 'one' key


 print (dict[2]) # Prints value for 2 key
 print (tinydict) # Prints complete dictionary
 print (tinydict.keys()) # Prints all the keys
 print (tinydict.values()) # Prints all the values
 This produce the following result −
 This is one
 This is two
 {'dept': 'sales', 'code': 6734, 'name': 'john'}
 ['dept', 'code', 'name']
 ['sales', 6734, 'john']
Input Statement
 a=input(“Enter a:”)

 a=int(input(“Enter a:”));

 a=eval(input("Enter three values:"))

 a, b, c=eval(input(“Enter a, b, c:”))
Matrices
 a=[
[1,2,3],
[4,5,6]
]

 a[0], a[1], a[0][0], a[0][2], a[1][2]

Note: Not Recommended as the len will be 2.


Basic Operators
 Types of Operator

 Arithmetic Operators

 Comparison (Relational) 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 Description Example


== If the values of two operands are equal, (a == b) is not true.
then the condition becomes true.
!= If values of two operands are not equal, (a!= b) is true.
then condition becomes true.
> If the value of left operand is greater (a > b) is not true.
than the value of right operand, then
condition becomes true.
< If the value of left operand is less than (a < b) is true.
the value of right operand, then condition
becomes true.
>= If the value of left operand is greater (a >= b) is not true.
than or equal to the value of right
operand, then condition becomes true.
<= If the value of left operand is less than or (a <= b) is true.
equal to the value of right operand, then
condition becomes true.
Basic Operators
 Assignment Operators
 Assume variable a holds 10 and variable b holds 20, then-
Operator Description Example
= Assigns values from right side operands to c = a + b assigns value
left side operand of a + b into c
+= It adds right operand to the left operand and c += a is equivalent to
assign the result to left operand c = c + a
-= It subtracts right operand from the left c -= a is equivalent to
operand and assign the result to left operand c = c - a
*= It multiplies right operand with the left c *= a is equivalent to
operand and assign the result to left operand c = c * a
/= It divides left operand with the right operand c /= a is equivalent to
and assign the result to left operand c = c / a
%= It takes modulus using two operands and c %= a is equivalent to
assign the result to left operand c = c % a
**= Performs exponential (power) calculation on c **= a is equivalent
operators and assign value to the left operand to c = c ** a
//= It performs floor division on operators and c //= a is equivalent
assign value to the left operand to c = c // a
Basic Operators
 Bitwise Operators
 Assume a = 60 = 0011 1100 and b = 13 = 0000 1101, then-
Operator Description Example

& 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-

Operator Description Example


and If both the operands are true (a and b) is False.
then condition becomes true.
or If any of the two operands (a or b) is True.
are non-zero then condition
becomes true.
not Used to reverse the logical Not(a and b) is True.
state of its operand.
Basic Operators
 Membership Operators
 Python’s membership operators test for membership in a
sequence, such as strings, lists, or tuples.

 There are two membership operators as explained below

Operator Description Example


in Evaluates to true if it finds a x in y, here “in” results in a
variable in the specified 1 if x is a member of
sequence and false otherwise. sequence y.
not in Evaluates to true if it does not x not in y, here “not in”
finds a variable in the specified results in a 1 if x is not a
sequence and false otherwise. member of sequence y.
Basic Operators
 Identity Operators
 Identity operators compare the memory locations of two
objects.
 There are two Identity operators explained below:

Operator Description Example


is Evaluates to true if the x is y, here ”is” results in 1
variables on either side of the if id(x) equals id(y).
operator point to the same
object and false otherwise.
is not Evaluates to false if the x is not y, here ”is
variables on either side of the not” results in 1 if id(x) is
operator point to the same not equal to id(y).
object and true otherwise.
Basic Operators
 Python Operator Precedence
 Operator Description
** Exponentiation (raise to the power)

~ + - Complement, unary plus and minus

* / % // Multiply, divide, modulo and floor division

+ - Addition and subtraction


>> << Right and left bitwise shift
& Bitwise 'AND'
^ | Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators


<> == != Equality operators
= %= /= //= -= += *= Assignment operators
**=
is is not Identity operators
in not in Membership operators
not or and Logical operators
Decision Making
 Simple if
 if expression:
statement(s)
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)
var2 = 0
if var2:
print ("2 - Got a true expression value")
print (var2)
print ("Good bye!")

Output:
1 - Got a true expression value
100
Good bye!
Decision Making
 if else
 if expression:
statement(s)
else:
statement(s)

amount=int(input(“Enter amount: “))


if amount<1000:
discount=amount*0.05
print ("Discount",discount)
else:
discount=amount*0.10
print ("Discount",discount)

print ("Net payable:",amount-discount)


Decision Making
 if else
Output:
Enter amount: 600
Discount 30.0
Net payable: 570.0

Enter amount: 1200


Discount 120.0
Net payable: 1080.0
Decision Making
 elif Statement
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Decision Making
 elif Statement
amount=int(input("Enter amount: "))
if amount<1000:
discount=amount*0.05
print ("Discount",discount)
elif amount<5000:
discount=amount*0.10
print ("Discount",discount)
else:
discount=amount*0.15
print ("Discount",discount)

print ("Net payable:",amount-discount)


Decision Making
 elif Statement
Enter amount: 600
Discount 30.0
Net payable: 570.0

Enter amount: 3000


Discount 300.0
Net payable: 2700.0

Enter amount: 6000


Discount 900.0
Net payable: 5100.0
Decision Making
 Nested if

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

print ("Good bye!")


Loops
 While Loop

The count is: 0


The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
Loops
 for Loop

for iterating_var in sequence:


statements(s)

for var in list(range(5)):


print (var)

Output:
0
1
2
3
4
Loops
 for Loop

for letter in 'Python': # traversal of a string sequence


print ('Current Letter :', letter)

Output:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Loops
 for Loop

fruits = ['banana', 'apple', 'mango']


for fruit in fruits: # traversal of List sequence
print ('Current fruit :', fruit)

print ("Good bye!")

Output:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Loops
 for Loop
 Iterating by Sequence Index

fruits = ['banana', 'apple', 'mango']


for index in range(len(fruits)):
print ('Current fruit :', fruits[index])

print ("Good bye!")

Output:
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Loops
 Break Statement

for letter in 'Python':


if letter == 'h':
break
print ('Current Letter :', letter)

Output:
Current Letter : P
Current Letter : y
Current Letter : t
Loops
 Continue Statement

for letter in 'Python':


if letter == 'h':
continue
print ('Current Letter :', letter)

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

• If the else statement is used with a for loop, the else


block is executed only if for loops terminates normally
(and not by encountering break statement).

• If the else statement is used with a while loop, the else


statement is executed when the condition becomes false.
Loops
 Using else Statement with Loops

numbers=[11,33,55,39,55,75,37,21,23,41,13]

for num in numbers:


if num%2==0:
print ('the list contains an even number')
break
else:
print ('the list does not contain even number')

Output:
the list does not contain even number
Numbers - Revisited
 Numbers
 Number Type Conversion
 Type int(x) to convert x to a plain integer.

 Type float(x) to convert x to a floating-point number.

 Type complex(x) to convert x to a complex number with real part


x and imaginary part zero.

 Type complex(x, y) to convert x and y to a complex number with


real part x and imaginary part y. x and y are numeric expressions.
Numbers - Revisited
 Numbers
 Mathematical Functions

Function Returns ( description )


abs(x) The absolute value of x: the (positive)
distance between x and zero.
math.ceil(x) The ceiling of x: the smallest integer not
less than x
x
math.exp(x) The exponential of x: e
math.floor(x) The floor of x: the largest integer not
greater than x
math.log(x) The natural logarithm of x, for x> 0
math.log10(x) The base-10 logarithm of x for x> 0 .
Numbers - Revisited
 Numbers
 Mathematical Functions
Function Returns ( description )
max(x1, x2,...) The largest of its arguments: the value
closest to positive infinity
min(x1, x2,...) The smallest of its arguments: the value
closest to negative infinity
pow(x, y) The value of x**y.
round(x [,n]) x rounded to n digits from the decimal
point.
math.sqrt(x) The square root of x for x > 0
Numbers - Revisited
 Numbers
 Random Number Functions
Function Description
random.choice(seq) A random item from a list, tuple, or string.
random.random() A random float r, such that 0 is less than or
equal to r and r is less than 1
random.seed([x]) Sets the integer starting value used in
generating random numbers. Call this function
before calling any other random module
function. Returns None.
random.shuffle(lst) Randomizes the items of a list in place. Returns
None.
random.uniform(x, y) A random float r, such that r is less than or
equal to x and r is less than y
random.randint(x, y) Return random integer in range [x, y], including
both end points.
Strings - Revisited
 Strings (Assume str to be a string variable)
Sr. Methods with Description
No.
1 str.capitalize()
Capitalizes first letter of string. Not in Place
2 str.isalnum()
Returns true if string has at least 1 character and all
characters are alphanumeric and false otherwise.
3 str.isalpha()
Returns true if string has at least 1 character and all
characters are alphabetic and false otherwise.
4 str.isdigit()
Returns true if string has at least 1 character and contains
only digits and false otherwise.
5 str.islower()
Returns true if string has at least 1 cased character and all
cased characters are in lowercase and false otherwise.
6 str.isspace()
Returns true if string contains only whitespace characters and
false otherwise.
Strings - Revisited
 Strings
Sr. Methods with Description
No.
7 str.isupper()
Returns true if string has at least one cased character and all
cased characters are in uppercase and false otherwise.
8 len(str)
Returns the length of the string
9 str.lower()
Converts all uppercase letters in string to lowercase. Not in
Place.
10 max(str)
Returns the max alphabetical character from the string str.
11 min(str)
Returns the min alphabetical character from the string str.
12 str.upper()
Converts lowercase letters in string to uppercase. Not in Place.
Lists - Revisited
 Delete List Elements

list = ['physics', 'chemistry', 1997, 2000]


print (list)
del list[2]
print ("After deleting value at index 2 : ", list)

Output:
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics',
'chemistry', 2000]
Lists - Revisited
 Basic List Operations

Python Expression Results Description


len([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Concatenation
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] Repetition
3 in [1, 2, 3] True Membership
for x in [1,2,3] : print 1 2 3 Iteration
(x,end=' ')
Lists - Revisited
 Built in List Functions and Methods (assume list to
be name of the variable)
Sr. Function with Description

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

def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

def printme( str ):


"This prints a passed string into this function"
print (str)
return
Python Functions
 Pass by reference vs value

 All parameters (arguments) in the Python language are


passed by reference.

 It means if you change what a parameter refers to within


a function, the change also reflects back in the calling
function.
Python Functions
 Pass by reference vs value

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return

# Now you can call changeme function


mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)

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

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4] # This would assign new reference in mylist
print ("Values inside the function: ", mylist)
return

# Now you can call changeme function


mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)

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.

 This means that local variables can be accessed only


inside the function in which they are declared, whereas
global variables can be accessed throughout the program
body by all functions.
Python Functions
 Global vs. Local Variables

total = 0 # This is a global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return

# Now you can call sum function


sum( 10, 20 )
print ("Outside the function global total : ", total )

Output:
Inside the function local total : 30
Outside the function global total : 0
Python Functions
 Global vs. Local Variables

total = 0 # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
global total
total = arg1 + arg2;
print ("Inside the function local total : ", total)
return

# Now you can call sum function


sum( 10, 20 )
print ("Outside the function global total : ", total )

Output:
Inside the function local total : 30
Outside the function global total : 30

Note: You can also return multiple values, e.g. return x, y


Miscellaneous
 del var_name
 del var1, var2
 type(5)
 type(5.6)
 type(5+2j)
 type(“hello”)
 type([‘h’,’e’])
 type((‘h’,’e’))
 Multiple Assignments
 a=b=c=1
 a, b, c = 1, 2, "john"
Numpy
 Numpy (Numeric/Numerical Python)
 Numpy is an open-source add-on module that provides
common mathematical and numerical routines as pre-
compiled fast functions

 It provides basic routines for manipulating large arrays


and matrices of numeric data.

 import numpy as np

 C:\\Python34\scripts>pip3.4 list

 C:\\Python34\scripts>pip3.4 install numpy


Numpy
 np.array
 Collection of same type of elements

 One dimensional array


Numpy
 np.array
 Two dimensional array
Numpy
 np.array
 Two dimensional array: reshape() & copy()

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

 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]
]
 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.

You might also like