Unit Iv - Python Functions, Modules and Packages
Unit Iv - Python Functions, Modules and Packages
Unit Iv - Python Functions, Modules and Packages
14 Marks
WHAT IS A FUNCTION IN PYTHON?
🞆A function is a block of organized, reusable code which
can be called whenever required. A function is a piece of
code that performs a particular task.
🞆Functions help break our program into smaller and
modular chunks. As our program grows larger and larger,
functions make it more organized and manageable.
🞆Furthermore, it avoids repetition and makes code
reusable
USE OF PYTHON BUILT-IN FUNCTIONS:
🞆Functions are self contained block of statements that act
like a program that perform specific task.
🞆The python interpreter has a number of functions that are
always available for use. These functions are called
built-in functions.
🞆E.g. print() functions prints the given object to the
standard output device.
TYPE DATA CONVERSION FUNCTIONS
🞆It is necessary to perform conversion between the built-
in types. To convert between types we simply use the
type name as a function.
🞆Python define type conversion functions to directly
convert one type of data type to another.
🞆Python Implicit Data Type Conversion:
It takes place either during compilation or during
run time and is handled directly by python.
EXAMPLE :
Converting integer to float
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
output
datatype of num_int: <Class ‘int’>
datatype of num_flo: <Class ‘Float’>
Value of num_new: 124.23
datatype of num_new:<Class ‘Float’>
PYTHON EXPLICIT DATA TYPE CONVERSION
🞆In Explicit Type Conversion, users convert the data
type of an object to required data type.
🞆We use the predefined functions like int(), float(), str(),
etc to perform explicit type conversion.
🞆This type conversion is also called typecasting because
the user casts (change) the data type of the objects
🞆Syntax :
(required_datatype)(expression)
Typecasting can be done by assigning the required data
type function to the expression.
CONVERSION FUNCTIONS
1. int(a,base) : This function converts any data type to integer.
‘Base’ specifies the base in which string is if data type is string.
2. float() : This function is used to convert any data type to a
floating point number.
3. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.
6. tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to set.
8. list() : This function is used to convert any data type to a list type.
9. dict() : This function is used to convert a tuple of order
(key,value) into a dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : This function converts real numbers to
complex(real,imag) number.
Example 1:- # Python code to demonstrate Type conversion # using int(),
float()
# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
Example 2:- # Python code to demonstrate Type conversion # using ord(), hex(),
oct()
# initializing
s = ‘A'
# printing character converting to integer
c = ord(s)
print ("After converting character to integer : ",end="")
print (c)
# printing integer converting to hexadecimal string
c = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (c)
# printing integer converting to octal string
c = oct(56)
print ("After converting 56 to octal string : ",end="")
print (c)
Output: After converting character to integer : 65
After converting 56 to hexadecimal string : 0x38
Example 3:- # Python code to demonstrate Type conversion using tuple(), set(), list()
# initializing string
s = ‘hello'
# printing string converting to tuple
c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)
# printing string converting to set
c = set(s)
print ("After converting string to set : ",end="")
print (c)
# printing string converting to list
c = list(s)
print ("After converting string to list : ",end="")
print (c)
OUTPUT:
After converting string to tuple : ('h', 'e', 'l', 'l', 'o')
After converting string to set : {'l', 'e', 'o', 'h'}
After converting string to list : ['h', 'e', 'l', 'l', 'o']
FORMATTING NUMBERS AND STRINGS
🞆The built-in format() function returns a formatted
representation of the given value controlled by the
format specifier.
🞆Syntax:
format(value,format)
e.g. x=12.345
print(format(x,".2f"))
Output :
12.35
PARAMETER VALUES-
🞆 < :- Left aligns the result within the available space
e.g x=10.23456 print(format(x,“<10.2f”)
Output: ‘10.23 ‘
🞆 > :- Right aligns the result within the available space
e.g. x=10.23456 print(format(x,“>10.2f"))
Output: ‘ 10.23 ‘
🞆 ^ :- Center aligns the result within the available space
e.g. x=10.23456 print(format(x,“^10.2f")) Output: ‘ 10.23 ‘
🞆 +, - :- Use a sign to indicate if the result is positive or negative
e.g. x=10.23456 y=-10.23456
print(format(x,"+"))
print(format(y,"-"))
Output: +10.23456
-10.23456
PARAMETER VALUES-
🞆, :- Use a comma as a thousand separator
e.g. x=10000000 print(format(x,","))
Output: 10,000,000
🞆_ :- Use a underscore as a thousand separator.
e.g. x=10000000 print(format(x,"_"))
Output: 10_000_000
🞆b :- binary format e.g. x=10
print(format(x,"b")) Output: 1010
🞆c :- convert the value to corresponding Unicode character.
🞆e : - Scientific character with a lower case e
🞆E :- Scientific character with a upper case E.
🞆f :- fix point number format
PARAMETER VALUES-
🞆 g :– General Format.
🞆 o : - octal format
🞆 x : – Hex Format, lower case
🞆 X :- Hex format, Upper case
🞆 % :– Percentage format
🞆 %10s :- String with width 10 in left justification
🞆 %-10s :- String with width 10 in Right justification
Example:
>>> place = "London"
>>> print ("%10s is not a place in France" % place) # Pad to the left
London is not a place in France
>>> print ("%-10s is not a place in France" % place) # Pad to the right
London is not a place in France
Example:-
x=10
print(format(x,"g"))
print(format(x,"o"))
print(format(x,"x"))
print(format(x,"X"))
print(format(x,"%"))
#Use "%" to convert the number into a percentage format:
txt = "You scored {:%}"
print(txt.format(0.25))
#Or, without any decimals:
txt = "You scored {:.0%}"
print(txt.format(0.25))
OUTPUT:
10
12
a
A
1000.000000%
You scored 25.000000%
You scored 25%
BUILT-IN MATHEMATICAL FUNCTIONS
🞆These are the functions which doesn’t require any
external code file/modules/ Library files.
🞆These are a part of the python core and are just built
within the python compiler hence there is no need of
importing these modules/libraries in our code.
BUILT-IN MATHEMATICAL FUNCTIONS
🞆min()- Returns smallest value among supplied
arguments.
e.g. print(min(20,10,30))
o/p 10
🞆max()- Returns largest value among supplied arguments.
e.g. print(max(20,10,30))
o/p 30
🞆pow()- Returns the value of x to the power of y. e.g.
print(pow(2,3))
o/p 8
BUILT-IN MATHEMATICAL FUNCTIONS
🞆 round()- Returns a floating point number that is rounded
version of the specified number, with the specified number
of decimals. The default number of decimals is 0, i.e it will
return nearest integer.
🞆 e.g. print(round(10.2345))
o/p 10
print(round(5.76543))
o/p 6
print(round(5.76543,2))
o/p 5.77
🞆 abs()- Returns the non negative value of the argument value.
e.g. print(abs(-5))
o/p 5
BUILT-IN FUNCTIONS(MATH MODULE):
🞆The second type of function requires some external
files(modules) in order to be used.
🞆The process of using these external files in our code is called
importing.(we need to import math.)
🞆ceil()- Returns smallest integral value greater than the number.
e.g. import math
print(math.ceil(2.3))
o/p 3
🞆floor()- Returns the greatest integral value smaller than the
number.
e.g. import math
print(math.floor(2.3))
o/p 2
BUILT-IN FUNCTIONS(MATH MODULE):
🞆cos()- Returns the cosine of value passed as argument.
The value passed in this function should be in radians.
e.g. import math
print(math.cos(3))
o/p -0.9899924966004454
🞆cosh()- Returns the hyperbolic cosine of x.
e.g. import math
print(math.cosh(3))
o/p 10.067661995777765
🞆copysign()- Returns x with sign of y.
e.g. import math
print(math.copysign(10,-12))
o/p -10.0
BUILT-IN FUNCTIONS(MATH MODULE):
🞆 exp()- Returns the exponential of x.
e.g. import math
print(math.exp(1)) # i.e (e)1
o/p 2.718281828459045
🞆 fabs()- Returns the absolute or positive value.
e.g. import math # here f for float
print(math.fabs(-20))
o/p 20.0
🞆 factorial()- Returns factorial of x.
e.g. import math
print(math.factorial(5))
o/p 120
🞆 fmod()- Returns the x % y. # here f for float
e.g. import math
print(math.fmod(50,20))
o/p 10.0
BUILT-IN FUNCTIONS(MATH MODULE):
🞆 log(a,(base))- Used to compute the natural logarithm(base e) of a.
e.g. import math
print(math.log(14))
o/p 2.6390573296152584
🞆 log2(a)- Used to compute the logarithm(base 2) of a.
🞆 e.g. import math
🞆 print(math.log2(14))
o/p 3.807354922057604
🞆 log10(a)- Used to compute the logarithm(base 10) of a.
🞆 e.g. import math
🞆 print(math.log10(14))
o/p 1.146128035678238
🞆 sqrt()- Returns the square root of x for x>0.
e.g. import math
print(math.sqrt(100))
o/p 10.0
🞆 trunc()- Returns the truncated integer of x.
e.g. import math
print(math.trunc(3.354))
o/p 3
STRING:
🞆 Like many other popular programming languages, strings in
Python are arrays of bytes representing Unicode characters.
🞆 However, Python does not have a character data type, a
single character is simply a string with a length of 1.
🞆 Square brackets can be used to access elements of the string.
🞆 String can be enclosed in single or double quotes.
🞆 Syntax: str_name=‘string’
🞆 Example:
Get the character at position 1 (remember that the first
character has the position 0):
a = "Hello, World!"
print(a[1])
STRING FORMATTING OPERATORS AND BUILT IN FUNCTIONS OF STRING
MANIPULATION
BUILT IN FUNCTIONS OF STRING MANIPULATION
BUILT IN FUNCTIONS OF STRING MANIPULATION
BUILT IN FUNCTIONS OF STRING MANIPULATION
USER DEFINED FUNCTIONS
🞆output: 16
ADVANTAGES OF USER DEFINED FUNCTIONS
1. It help to decompose a large program into small segments which
makes program easy to understand, maintain and debug.
2. We can call python function any number of times in a program
and from any place in a program.
3. Reusability is the main achievement of python functions.
4. Functions in python reduces the overall size of the program.
5. We can track a large python program easily when it is divided
into multiple functions.
6. By using functions, we can avoid rewriting same logic/code
again and again in a program
CONCEPT OF ACTUAL AND FORMAL
PARAMETERS: (PARAMETER PASSING)
Actual Parameters:
🞆 The parameters used in the function call are called
actual parameters. These are the actual values that are
passed to the function.
🞆The data types of actual parameters must match with the
corresponding data types of formal parameters(variables)
in the function definition.
1. They are used in the function call.
2. They are actual values that are passed to the function
definition through the function call.
3. They can be constant values or variable names(such a
local or global)
FORMAL PARAMETERS:
🞆The parameters used in the header of function definition are
called formal parameters of the function.
🞆These parameters are used to receive values from the calling
function.
🞆1. They are used in function header.
🞆2. They are used to receive the values that are passed to the
function through function call.
🞆3. They are treated as local variables of a function in which
they are used in the function header
EXAMPLE:
def cube(x): # formal parameters
return x*x*x
result=cube(7) # actual parameters
print(result)
Output: 343
CALL BY OBJECT REFERENCE:
🞆Python utilizes a system, which is known as “Call by Object
Reference” or “Call by assignment”.
🞆In the event that you pass arguments like whole numbers,
strings or tuples to a function, the passing is like call-by-
value because you can not change the value of the immutable
objects being passed to the function.
🞆Whereas passing mutable objects like list, set, dictionaries
byte,array can be considered as call by reference because
when their values are changed inside the function, then it will
also be reflected outside the function
EXAMPLE: PYTHON CODE TO DEMONSTRATE CALL BY VALUE
string = "Hello"
def test(string):
string = "Hello World"
print("Inside Function:", string)
test(string)
print("Outside Function:", string)
Output:
Inside Function: Hello World
Outside Function: Hello
EXAMPLE : PYTHON CODE TO DEMONSTRATE CALL BY
REFERENCE
def add_more(list):
list.append(50)
print("Inside Function", list)
mylist = [10,20,30,40]
add_more(mylist)
print("Outside Function:", mylist)
Output:
Inside Function [10, 20, 30, 40, 50]
Outside Function: [10, 20, 30, 40, 50]
FUNCTION ARGUMENTS:
🞆Many built-in functions need arguments to be passed
with them. Many functions require two or more
arguments. The value of argument is always assigned to
a variable known as parameter.
🞆There are four types of arguments using which can be
called are
required arguments,
keyword arguments,
default arguments and
variable length arguments.
REQUIRED ARGUMENTS:
🞆These are the arguments passed to a function in correct
positional order. Here the number of arguments in the function
call should match exactly with the function definition.
🞆Example: Required Arguments
def printme(str):
"This prints a passed string into this function"
print(str)
return
# Call printme function
printme() # required arguments
Output: Traceback (most recent call last): File "D:\python
programs\sample.py", line 8, in printme() TypeError: printme()
missing 1 required positional argument: 'str'
KEYWORD ARGUMENTS:
🞆These are the arguments related to the function calls. When
we use it in the function call, the caller identifies the
arguments by the parameter name
🞆This allows us to skip arguments or place them out of order
because the python interpreter is able to use the keywords
provided to match the values with parameters.
🞆Example 1: Keyword Arguments
def printme(str):
"This prints a passed string into this function“
print(str)
return
# Call printme function
printme(str="My string")
Output: My string
DEFAULT ARGUMENTS:
🞆A default argument is an argument that assumes a default
value if a value is not provided in the function call for that
argument.
🞆Example: Default Arguments
def printinfo(name,age=35):
"This prints a passed info into this function"
print("Name: ",name)
print("Age: ",age)
return
# Call printinfo function
printinfo(age=40,name="Amol")
printinfo(name="Kedar")
Output: Name: Amol Age: 40
Name: Kedar Age:35
VARIABLE LENGTH ARGUMENTS:
🞆 In many cases where we are required to process a function with more number of
arguments than we specified in the function definition. These types of arguments
are known as variable length arguments.
🞆 Example : Variable length Arguments
def printadd(farg,*args):
"To add given numbers"
print("Output is: ",farg)
sum=0
for i in args:
sum+=i
print("sum of all numbers",(farg+sum))
return
# Call printadd function
printadd(5,10)
printadd(5,10,20,30)
Output: Output is: 5
sum of all numbers 15
Output is: 5
sum of all numbers 65
RETURN STATEMENT:
🞆 The return statement return[expression] exits a function,
alternatively going back an expression to the caller.
🞆 A return statement with no arguments is the same as
return none.
🞆 Syntax: return(expression)
🞆 Example
def sum(a1,a2):
t=a1+a2
print(“Sum:”,t)
return t
Result=sum(10,20)
o/p:
Sum:30
SCOPE OF VARIABLES:
🞆All variables in a program may not be available at all
areas in that program. This relies on upon where you have
announced a variable.
🞆There are two basic scopes of variables in python
1. Local variables:
a) When we declare a variable inside a function, it becomes
a local variable.
b) Its scope is limited only to that function where it is
created.
c) That means the local variable is available only in that
function but not outside that function.
SCOPE OF VARIABLES:
2. Global variables:
a) When we declare a variable above a function it becomes a global
variable.
b) Such variables are available to all functions which are written after
it.
Output:
Addition= 30
Subtraction= -10
Multiplication= 200
Division= 0.5
IMPORTING MODULES:
🞆Import statement is used to import a specific module by using
its name.
🞆Import statement creates a reference to that module in the
current namespace. After using import statement we can refer
the things defined in that module.
🞆Use import statement to make use of module
e.g. Import employee
• In this case we have to access the functions in employee
module using employee.hra(), employee.da() etc.
To avoid this we can use
from employee import *
from employee import hra, da
Example: using from x import *
from p1 import *
print("Addition= ",add(10,20))
print("Multiplication= ",mul(10,20))
Output:
Addition= 30
Multiplication= 200
import p1 as m
print(‘addition is :’,m.add)
PYTHON BUILT-IN MODULES:
🞆A module is a collection of python objects such as
functions, classes and so on.
🞆Python interpreter is bundled with a standard library
consisting of large number of built-in modules.
🞆Built-in modules are generally written in C and bundled
with python interpreter in precompiled form. A built-in
module may be a python script(.py) containing useful
utilities.
🞆A module may contain one or more functions, classes,
constants or any other python resources.
NUMERIC AND MATHEMATICAL MODULES:
🞆This module provides numeric and math related functions
and data types. Following are the modules which are
classified as numeric and mathematical modules.
1. numbers(Numeric abstract base classes)
2. math(Mathematical functions)
3. cmath(Mathematical functions for complex numbers)
4. decimal(Decimal fixed point and floating point arithmetic)
5. fractions(Rational numbers)
6. random(Generate pseudo random numbers)
7. Statistics(Mathematical statistics functions)
1. MATH MODULE
🞆The math module is a standard module in Python and is
always available.
🞆To use mathematical functions under this module, you have
to import the module using import math.
🞆It gives access to hyperbolic, trigonometric and logarithmic
functions for real numbers
🞆Example:
# importing built-in module math 🞆 Output:
import math 🞆 5.0
# using square root(sqrt) function contained
🞆 3.14159265359
# in math module
print (math.sqrt(25)) 🞆 114.591559026
4. Fractions module:
🞆 A fraction is a number which represents a whole number being
divided into multiple parts.
🞆Python fraction module allows us to manage fractions in our
python programs
🞆 Example:
import fractions
for num,decimal in [(3,2),(2,5),(30,4)]:
fract=fractions.Fraction(num,decimal)
print(fract)
Output:
3/2
2/5
15/2
5. Random module:
🞆 Sometimes we want the computer to pick a random number in a
given range or a list.
🞆 To perform this random module is used. This function is not
accessible directly, so we need to import random module and then
we need to call this function using random static object.
🞆 Example:
import random
print(random.random())
print(random.randint(10,20))
Output: :- 0.8709966760966288
:- 16
6. Statistics module:
🞆 It provides access to different statistics functions such as mean, median, mode,
standard deviation.
🞆 Example:
import statistics
print(statistics.mean([2,5,6,9]))
print(statistics.median([1,2,3,8,9])) print(statistics.mode([2,5,3,2,8,3,9,4,2,5,6]))
print(statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5]))
Output:
5.5
3
2
1.3693063937629153
FUNCTIONAL PROGRAMMING MODULES:
🞆This modules provide functions and classes that support a
functional programming style and general operations on
callable.
🞆Following modules are used here
1. Itertools 2. Functools 3. operator
1. Itertools Module:
🞆 It provide us various ways to manipulate the sequence
while we are traversing it.
🞆 Python itertools chain() function just accepts multiple
iterable and return a single sequence as if all items belongs
to that sequence.
🞆Example:
from itertools import *
for value in chain([1.3,2.51,3.3],['c++','python','java']):
print(value)
🞆output:
1.3
2.51
3.3
c++
python
java
2. functools Module:
🞆It provide us various tools which allows and encourage us to
write reusable code.
🞆Python functools partial() functions are used to replace
existing functions with some arguments already passed in. It
also creates new version of the function in a well documented
manner.
🞆Example: Suppose we have a function called multiplier which
just multiplies two numbers. Its definition looks like:
def multiplier(x,y):
return x*y
🞆 But what happens when we need 1000 such functions? Here we can use partial
functions:
from functools import partial
def multiplier(x,y):
return x*y
double=partial(multiplier,y=2)
triple=partial(multiplier,y=3)
print(“Double of 5 is {}”.format(double(5)))
print(“Triple of 5 is {}”.format(triple(5)))
🞆 Output:
Double of 5 is 10
Triple of 5 is 15
3.Operator Module:
🞆The operator module supplies functions that are equivalent to
python’s operators. These functions are handy in cases where
callables must be stored, passed as arguments or returned as
function results.
🞆Function supplied by operator module are
abs(a)-absolute add(a,b)-addition
and_(a,b)- logical truediv(a,b)- division
eq(a,b)- equal to gt(a,b)- greater than
le(a,b)- less than mod(a,b)- modulus
mul(a,b)-multiplication or_(a,b)- logical or
not_(a)- logical not xor(a,b)- logical xor
NAMESPACE AND SCOPING:
🞆A namespace is a system to have a unique name for each and
every object in python.
🞆An object might be a variable or a method.
🞆Python itself maintains a namespace in the form of a python
dictionary.
🞆Python interpreter understands what exact method or variable
one is trying to point to in the code, depending upon the
namespace.
🞆Name means an unique identifier while space talks something
related to scope.
🞆Name might be any python method or variable and space
depends upon the location from where is trying to access a
variable or a method.
TYPES OF NAMESPACE:
🞆Local Namespace: This namespace covers the local names
inside a function. Python creates this namespace for every
function called in a program.
🞆Global Namespace: This namespace covers the names from
various imported modules used in a project. Python creates
this namespace for every module included in the program.
🞆Built-in Namespace: This namespace covers the built-in
functions and built-in exception names. Python creates it as
the interpreter starts and keeps it until we exit.
PYTHON VARIABLE SCOPING:
🞆Scope is the portion of the program from where a namespace
can be accessed directly without any prefix.
🞆 At any given moment there are atleast following three nested
scope.
1. Scope of the current function which has local names. 2.
Scope of the module which has global names.
3. Outermost scope which has built-in names.
🞆When a reference is made inside a function the name is
searched in the local namespace, then in the global namespace
and finally in the built-in namespace.
PYTHON VARIABLE SCOPING:
🞆If there is a function inside another function, a new scope is
nested inside the local scope.
🞆Python has two scopes
• Local scope variable- All variables which are assigned inside
a function.
• Global scope variable-All those variables which are outside
the function termed
# EXAMPLE OF GLOBAL AND LOCAL SCOPE
Import math
global_var=30 # global scope
def scope():
local_var=40 #local scope
print(global_var)
print(local_var)
print(math.pi) #Built in Scope
scope()
print(global_var)
Output:
30
40
3.1415
30
PYTHON PACKAGES: INTRODUCTION-
🞆Suppose we have developed a very large application that
includes many modules. As the number of modules
grows, it becomes difficult to keep track of them as they
have similar names or functionality.
🞆It is necessary to group and organize them by some mean
which can be achieved by packages.
🞆A package is a hierarchical file directory structure
that defines a single python application environment
that consists of modules and subpackages and sub-
subpackages and so on.
🞆Packages allow for a hierarchical structuring of the module
namespace using dot notation.
🞆A package is a collection of python modules i.e. a package is
a directory of python modules containing an additional _
_init_ _.py file.
E.g Phone/_ _init_ _.py
WRITING PYTHON PACKAGES-
🞆To create a package in Python, we need to follow these
three simple steps:
1. First, we create a directory and give it a package
name, preferably related to its operation.
2. Then we put the classes and the required functions in
it.
3. Finally we create an __init__.py file inside the
directory, to let Python know that the directory is a
package.
EXAMPLE TO WRITE PYTHON PACKAGES-
🞆 Create a directory named mypkg and create a __init__.py file and
save in the mypkg directory so that mypkg will be considered as
package.
🞆 Create file p1.py in the mypkg directory and add this code
def m1():
print("First Module")
🞆 Create file p2.py in the mypkg directory and add this code
def m2():
print("second module")
🞆 Create file pkgsample.py and add this code
import math
print(math.pi)
o/p :
3.141592653589793
🞆Another well known mathematical constant defined in the
math module is e.
🞆It is called Euler’s number and it is a base of the natural
Logarithm.
🞆It value is 2.718281828459045
🞆e.g import math
print(math.e)
o/p: 2.718281828459045
2. NumPy:
🞆NumPy stands for “Numeric Python”.
• NumPy is the fundamental package for scientific computing
with python.
• It provides a high performance multidimensional array object
and tools for working with these arrays.
• An array is a table of elements (usually numbers) all of the
same type, indexed by a tuple of positive integers and
represented by a single variable. NumPy’s array class is called
ndarray. It is also known by the alias array.
• In NumPy arrays the individual data items are called elements.
Dimensions are called axes.
• The size of NumPy arrays are fixed , once created it cannot be
changed again.
• NumPy arrays are great alternatives to python lists.
🞆A one dimensional array has one axis indicated by Axis-
0. That axis has five elements in it, so we say it has
length of five.
🞆A two dimensional array is made up of rows and
columns. All rows are indicated by Axis-0 and all
columns are indicated by Axis-1.
🞆If Axis-0 in two dimensional array has three elements, so
its length is three and Axis-1 has six elements so its
length is 6.
🞆Using NumPy , a developer can perform the following
operations:
1. Mathematical and logical operations on arrays.
2. Fourier transforms and routines for shape manipulation.
3. Operations related to linear algebra.
4. NumPy has in-built functions for linear algebra and random
number generation.
ARRAY OBJECT:
🞆 NumPy’s main object is the homogeneous multidimensional
array. It is a table of elements(usually numbers) all of same
type, indexed by a tuple of positive integers.
🞆 In NumPy dimensons are called as Axes. NumPy’s array
class is called ndarray. It is also known by the alias array.
Basic attributes of the ndarray class are as follow:
•shape- A tuple that specifies the number of elements for each
dimension of array.
• size- The total number of elements in the array.
• ndim- Determines the dimension of an array.
• nbytes- Number of bytes used to store the data.
• dtype- Determines the datatype of elements stored in array.
1)Example
import numpy as np
a=np.array([10,20,30])
print(a)
2) Example
arr=np.array([[1,2,3],[4,5,6]])
print(arr)
type(arr) #<class ‘numpy.ndarray’>
print("No. of dimension: ",arr.ndim) #2
print("Shape of array: ",arr.shape) #(2,3)
print("Size of array: ",arr.size) #6
print("Type of elements in array: ",arr.dtype) # int32
print("No. of bytes: ",arr.nbytes) # 24
3. SciPy:
• SciPy is a library that uses NumPy for more mathematical
functions.
• SciPy uses NumPy arrays as the basic data structure and
come with modules for various commonly used tasks in
scientific programming, including linear algebra,
integration (calculus), ordinary differential equation
solving and signal processing.
• SciPy is organized into subpackage covering different
scientific computing domains. These are as given …
🞆e.g. using linalg sub package of SciPy
import numpy as np
from scipy import linalg
a=np.array([[1.,2.],[3.,4.]])
linalg.inv(a) # find inverse of array
o/p: array([[-2.,1.],[1.5,-0.5]])
pandas.Series(data,index,dtype,copy)
structure with homogeneous
data. 🞆 2)Example:
1) Example: import pandas as pd
import pandas as pd data=[10,20,30,40,50]
import numpy as np index=[‘a’,’b’,’c’,’d’,’e’]
arr= np.array([2,4,6,8,10,20]) si=pd.Series(data,index)
si=pd.Series(arr) Print(si)
Print(si)
Output:
Output:
a 10
0 2
1 4 b 20
2 6 c 30
3 8 d 40
4 10
e 50
5 20
DataFrame-
• Dataframes are two dimensional structures which consist of columns
and rows.
• It can be used to store the data of any type.
Syntax: pandas.DataFrame(data,index,column,dtype,copy)
e.g. import pandas as pd
dict1={'a':1.1,'b':2.1,'c':3.1,'d':4.1}
dict2={'a':5.1,'b':6.1,'c':7.1,'d':8.1}
data={'Col 1':dict1,'Col 2':dict2}
df=pd.DataFrame(data)
print(df)
Output: Col1 Col2
a 1.1 5.1
b 2.1 6.1
c 3.1 7.1
d 4.1 8.1
Panel-
•Panel is a three dimensional data structure with homogeneous
data.
•It is hard to represent the panel in graphical representation.
•But a panel can be illustrated as a container of DataFrame. It
takes following arguments
1. data: The data can be of any form like ndarray, list, dict, map,
DataFrame
2. item: axis 0, each item corresponds to a dataframe contained
inside.
3. major_axis:axis 1, it is the index (rows) of each of
DataFrames.
4. minor_axis: axis 2, it is the column of DataFrames.
5. dtype: The data type of each column.
6. copy: It takes a Boolean value to specify whether or not to
copy the data. The default value is false.
EXAMPLE 1: # CREATING AN EMPTY PANEL
import pandas as pd
import numpy as np
data = np.random.rand(1,2,3)
p = pd.Panel(data)
print (p)
🞆Output:
<class ‘pandas.core.panel.Panel’>
Dimensions: 1 (items) x 2 (major_axis) x 3 (minor_axis)
Items axis: 0 to 0
Major_axis axis: 0 to 1
Minor_axis axis: 0 to 2
USER DEFINED PACKAGES:
🞆We organize a large number of files in different folders and
subfolders based on some criteria, so that we can find and
manage them easily.
🞆In the same way a package in python takes the concept of the
modular approach to next logical level.
🞆A package can contain one or more relevant modules.
🞆Physically a package is actually a folder containing one or more
module files.
EXAMPLE TO CREATE AND ACCESS THE PACKAGES-
• Create a directory named mypkg1 and create a __init__.py file and
save in the mypkg1 directory so that mypkg1 will be considered as
package.
• Create modules message.py and mathematics.py with following code:
message.py
def sayhello(name):
print("Hello “,name)
return
mathematics.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
🞆Create p1.py with the code given
p1.py
from mypkg1 import mathematics
from mypkg1 import message
message.sayhello("Amit")
x=mathematics.power(3,2)
print("power(3,2) :",x)
🞆Output
Hello Amit
power(3,2) : 9
🞆 Using __init__.py file:
Normally __init__.py file is kept empty. However it can be used
to choose specific functions from modules in the package folder
and make them available for import.
__init__.py
from .mathematics import average,power
from .message import sayhello
• Create a test.py file and the specified functions in __init_.py can
now be imported in the interpreter session or another executable
script.
test.py
from mypkg1 import power,average,sayhello
sayhello("Amol")
x=power(3,2)
print("power(3,2): ",x)
Output:
Hello Amol
power(3,2): 9