Unit Iv
Unit Iv
Unit Iv
*****************************************************
*** UNIT-IV Python Functions,Modules and Packages ***
*****************************************************
• Functions:
- Function is a block of code.
- Function is a piece of code that performs particular task.
- Whenever we want, we can call that function.
- There are two different types of functions.
1) Built-in functions.
2) User defined functions.
• Built-in Functions:
- The function which is already exists and we can just re-use it.
- It is also known as predefined function.
- We will not write definition of these functions, we can simply call
these functions.
- Examples:
Following are the built-in mathematical functions.
floor Number=8
-Program:
import math;
m=max(20,35);
print("Largest Number=",m);
m=min(20,35);
print("Smallest Number=",m);
m=pow(2,3);
print("Power of 2^3 =",m);
m=round(20.55);
print("Rounded Number=",m);
m=abs(-23);
print("Abs Result=",m);
m=math.ceil(8.1);
print("Ceil Number=",m);
m=math.floor(8.1);
print("Floor Number=",m);
-OUTPUT:
Largest Number= 35
Smallest Number= 20
Power of 2^3 = 8
Rounded Number= 21
Abs Result= 23
Ceil Number= 9
Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-IV Python Functions,Modules and Packages
Floor Number= 8
2) Calling Function:
- The def statement only creates function but not call it.
- Syntax:
FunctionName(Arguments);
- Example:
vjtech();
- When calling function is executed then program controller goes to
function definition.
- After successfully execution of function body, program controller
come back to end of the calling function.
- The arguments which we passes through the calling function is
known as Actual Arguments.
Program-1:
def vjtech(): #function definition
print("This is user defined function");
Program-2:
def EvenOdd(): #function definition
no=int(input("Please enter any number:"));
if(no%2==0):
print("Number is EVEN!!!");
else:
print("Number is ODD!!!");
=====================
Functions Arguments
======================
- Many built-in functions or user defined functions need arguments
on which they will operate.
- The value of argument is assigned to variable is known parameter.
- There are four types of arguments:
1) Required Arguments
2) Keyword Arguments
3) Default Arguments
4) Variable length Arguments
✓ #Test case-1:
def Addition(a,b):
c=a+b;
print("Addition of two numbers=",c);
Addition(10,20) #Required Arguments
OUTPUT:
Addition of two numbers=30
✓ #Test Case-2:
def Addition(a,b):
c=a+b;
print("Addition of two numbers=",c);
Addition()
OUTPUT:
Traceback (most recent call last):
File "main.py", line 4, in <module>
Addition()
TypeError: Addition() missing 2 required positional arguments: 'a'
and 'b'
• ***Keyword Arguments:
def display(name,age):
print("Student Name:",name)
print("Student Age :",age)
display(name="Mohan",age=35)
OUTPUT:
Student Name: Mohan
Student Age : 35
• ***Default Arguments:
- A default argument is an argument that assumes a defualt value if a
value is not provided in the function call.
- If we pass value to the default arguments then defualt value got
override.
- Example:
def display(name,age=23):
print("Student Name:",name)
print("Student Age :",age)
display("James")
OUTPUT:
Student Name: James
Student Age : 23
OUTPUT:
Value of m= (100, 200, 300, 400, 500, 600, 700, 800, 900)
=======================
return Statement:
=======================
- The return statement is used to exit function.
- The return statement is used to return value from the function.
- Function may or may not be return value.
- If we write return statement inside the body of function then it
means you are something return back to the calling function.
- Syntax:
return(expression/value);
- Example:
def Addition():
a=int(input("Enter First Number:"));
b=int(input("Enter Second Number:"));
c=a+b;
return c;
m=Addition();
print("Addition of Two Number=",m);
OUTPUT:
Enter First Number:100
Enter Second Number:200
m,n,p=Addition();
print("Addition of ",m," and ",n," is ",p);
====================
Scope of Variable
====================
- Scope of variable means lifetime of variable.
- Scope of variable decide visibility of variable in program.
- According to variable visibility, we can access that variable in
program.
- There are two basic scopes of variables in Python:
✓ Local Variables:
- Local variables can be accessed only inside the function in which
they are declared.
✓ Global Variables:
- Global variables can be accessed throughout the program.
- We can access global variable everywhere in the program.
- Global variables are declared outside the all functions.
- Global variables are alive till the end of the program.
- Global variable is destroyed when the program controller exit out of
the program.
- Example:
a=100; #Global variable
def display():
b=200; #local variable
print("Local Variable b = ",b);
print("Global Variable a= ",a);
display();
=====================
Recursion Function:
====================
- When function called itself is knowns as recursion function.
- A function is said to be recursive if it calls itself.
- Example:
def fact(n):
if n==0:
return 1;
else:
return n*fact(n-1);
result=fact(5);
print("Factorial of 5 number is ",result);
OUTPUT:
Factorial of 5 number is 120
✓ Advantages of Recursion:
1) Recursion functions make the code look clean.
2) Complex task we can manage easily using recursion.
3) Sequence generation is easier using recursion.
✓ DisAdvantages of Recursion:
Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-IV Python Functions,Modules and Packages
====================
***Modules***
====================
- Modules are primarily the .py file which contains python
programming code defining functions,clas,variables,etc.
- File containing .py python code is known as module.
- Most of time, we need to use existing python code while
developing projects.
- We can do this using module feature of python.
- Writing module means simply creating .py file which can contain
python code.
- To include module in another program, we use import statement.
- Module helps us to achive resuablility features in python.
- Follow below steps while creating module:
1) Create first file as python program with extension .py.This is your
module file where we can write functions, classes and variables.
2) Create second file in the same directory which access module
using import statement. Import statement should be present at top
of the file.
- Example:
=============================================
Different Ways of importing modules in Python
==============================================
- While accessing modules, import statement should be written at
top of the file.
- import statement is used to import specific module using its name.
- There are different ways of importing modules.
1) Use "import ModuleName":
- In this approach while accessing functions, we have to use module
name again and again.
- It means we use sytanx like ModuleName.FunctionName();
- Example:
✓ Step-1: #creating CheckEvenOdd.py module
def EvenOdd():
print("Enter Any Integer Number:");
no=int(input());
if(no%2==0):
print("Number is EVEN!!!");
else:
print("Number is ODD!!!");
- Example:
✓ Step-1: #creating Arithmetic.py module
def Add(a,b):
c=a+b;
print("Addition of two numbers=",c);
def Sub(a,b):
c=a-b;
print("Subtraction of two numbers=",c);
def Div(a,b):
c=a/b;
print("Division of two numbers=",c);
def Mul(a,b):
c=a*b;
print("Multiplication of two numbers=",c);
- Example:
✓ Step-1: #creating CheckEvenOdd.py module
def EvenOdd():
print("Enter Any Integer Number:");
no=int(input());
if(no%2==0):
print("Number is EVEN!!!");
else:
print("Number is ODD!!!");
VJ.EvenOdd();
▪ ##Practice Program-1:
def Cube(no):
result=no*no*no;
return(result);
m=Cube(x);
print("Cube of given number=",m);
========================
Python Built-in Modules:
========================
**Math & cmath Modules:
- Python provided two important modules named as math & cmath
using this we can perform certain operations. We can access
functions related to hyperbolic, trigonometric and logarithmic topics.
- Examples.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
#For Math & cmath Modules
import math
import cmath
x=math.cos(60);
print("Result of cos(60) =",x);
x=math.pow(2,3);
print("Result of pow(2,3) =",x);
x=math.sqrt(9);
print("Result of sqrt(9) =",x);
===================
***Statistics Module:
===================
- This module provides functions which calculate
mean,mode,median,etc
- Example:
import statistics
x=statistics.mean([2,5,6,9]);
print("Result of mean([2,5,6,9])=",x);
x=statistics.median([1,2,3,8,9]);
print("Result of median([1,2,3,8,9]=",x);
x=statistics.mode([2,5,3,2,8,3,9,4,2,5,6]);
print("Result of mode([2,5,3,2,8,3,9,4,2,5,6])=",x);
OUTPUT:
Result of mean([2,5,6,9])= 5.5
Result of median([1,2,3,8,9]= 3
Result of mode([2,5,3,2,8,3,9,4,2,5,6])= 2
==========================
***Python Packages***
==========================
- Package is a collection of modules and sub-packages.
- This helps you to achieve reusablility in python.
- It will create hierarchical structure of the modules and that we can
access it using dot notation.
- Package is collection of python modules.
- While creating package in python, we have to create empty file
named as __init__.py and that file should be present under the
package folder.
- Follow below steps while creating packages:
1) First, we have to create directory and give package name.
2) Second, need to create modules and put it inside the package
directory.
3) Finally, we have to create empty python file named as __init__.py
file. This file will be placed inside the package directory. This will let
python know that the directory is a package.
4) Access package in another file using import statement.
- Example:
✓ STEP-1: Create Module1.py file
def display():
print("This is display method of module-1");
=====================
Predefined Packages:
=====================
- Predefined packages are numpy,scipy,matplotlib,pandas,
✓ numpy:
- Numpy is the fundamental package for scientific computing with
python.
- Example:
import numpy
a=numpy.array([[10,20,30],[40,50,60]]);
print("Array Elements:",a);
print("No of dimension:",a.ndim);
print("Shape of array:",a.shape);
print("Size of array:",a.size);
print("Data Type of array elements:",a.dtype);
print("No of bytes:",a.nbytes);
OUTPUT:
Array Elements: [[10 20 30]
[40 50 60]]
No of dimension: 2
Shape of array: (2, 3)
Size of array: 6
Data Type of array elements: int32
No of bytes: 24
===================
scipy package
===================
- scipy is a library that uses numpy for more mathematical functions.
- Scipy uses numpy arrays as the basic data structre and comes with
modules for various commonly used task in scientific programming,
including algebra,integration,differential equation and signal
processing.
- We use below statement for installation of scipy package.
- Example1:
import numpy as np
from scipy import linalg
a=np.array([[1.,2.],[3.,4.]]);
print(linalg.inv(a)) #find inverse of array
OUTPUT:
Python Programming by Mr.Vishal Jadhav Sir’s(VJTech Academy,contact us:+91-9730087674)
UNIT-IV Python Functions,Modules and Packages
[[-2. 1. ]
[ 1.5 -0.5]]
- Example2:
import numpy as np
from scipy import linalg
a=np.array([[1,2,3],[4,5,6],[7,8,9]]);
print(linalg.det(a)) #find determinant of array
OUTPUT:
0.0
====================
Matplotlib package
====================
- this package is used for 2D graphics in python programming
language.
- It can be used in python script,shell,web application servers and
other graphical user interface toolkits.
- There are various plots which can be created usinh python
matplotlib like bar graph,histogram,scatter plot,area plot,pie plot.
- Following statement used to install this package:
- Example1:
#line plot
from matplotlib import pyplot;
x=[2,6,10,2];
y=[2,8,2,2];
pyplot.plot(x,y);
pyplot.show();
- Example2:
#for bar graph
from matplotlib import pyplot
x=[2,4,8,10];
y=[2,8,8,2];
pyplot.xlabel('X-Axis');
pyplot.ylabel('Y-Axis');
pyplot.bar(x,y,label="Graph",color='r',width=0.5)
pyplot.show();
==================
Pandas package
==================
- Pandas is an open source python library providing high
performance data manipulation and analysis tool using its powerful
data structure.
- It is built on the numpy package and its key data structure is called
the DataFrame.
- DataFrame allow you to store and manipulate data in tabular
format.
- Following statement we use for installation of Pandas
- Example1:
#using dataframe data structure of panda.
dict={"Name":["Vishal","Mohan","Soham","Nilam"],"Salary":[12000,
13000,67000,11000]};
df=pd.DataFrame(dict);
print(df);
OUTPUT:
Name Salary
0 Vishal 12000
1 Mohan 13000
2 Soham 67000
3 Nilam 11000
VJTech Academy…