Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 57

Chapter 4

P Y T H O N F UN CT I O N S ,
M O D U L E S AN D PA CK AG E S
Functions
 A function is a set of statements that take inputs, do some
specific computation and produces output.

 The idea is to put some commonly or repeatedly done


task together and make a function, so that instead of
writing the same code again and again for different
inputs, we can call the function.
 2 types of functions:-
o User Defined Functions
o Built-in Functions
User Defined Function

The function can be defined using the def.

Syntax:-

def function_name(parameters):
statements
Create and Calling a Function

Creating a function: In Python, we can use def keyword to


define the function.
Syntax: def my_function():
function-suite
return
Calling a function: To call the function, use the function name
followed by the parentheses.
def hello_world():
print("hello world")
hello_world() #Function calling
Output:
hello world
Arguments in Function

Arguments in function:
The information into the functions can be passed as
the argumenta. The arguments are specified in the
parentheses. We can give any number of arguments,
but we have to separate them with a comma.
Example
#defining the function
def func (name):
print("Hi ",name);
#calling the function
func("ABC")
Output: hi ABC
return Statement:

return Statement:
The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no arguments
is the same as return None.
Example
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function: ", total
return total;
# Now you can call sum function
total = sum(10, 20 );
print "Outside the function: ", total
Output:
Outside the function: 30
User Defined Functions
Program using User Defined function

def test_fun():
print("this is function definition")
test_fun()

O/P:-
>>>
this is function definition
>>>
Function Calling
 The function call is a statement that invokes the
function.
 When a function is called, the program control jumps
to the definition of the function and executes the
statements present in the function body.
 Once all the statements in function body get
executed, the control goes back to the calling
function.
Syntax:-
function_name()
Example:-

def print_msg():
print("hello")
print("welcome to python")

print_msg()

O/P:-
>>>
hello
welcome to python
>>>
Function Argument and Parameter passing
The argument is a value that is passed to the function
when it is called.
Syntax:-
function_name(variable1,variable2,variable3,….)
On the calling side, it is an argument and on the
function side, it is a parameter.
Return Statement

The value can be returned from a function using the


keyword return.

Syntax:-
return[expression_list]
Program to compute area of circle using
function and a return statement
def areacircle(r):
pi=3.14
result=pi*r*r
print("the result of circle")
return result
O/P:-
>>> areacircle(10)
the result of circle
314.0
>>>
Difference Between Local variable and Global
variable
Sr.N Local Variable Global Variable
o
1 A variable which is declared inside A variable which is declared outside
a function is called as local the function is called as local variable.
variable.

2 Accessibility of variable is only Accessibility of variable is throughout


within the function in which it is the program. All function in the
declared. program can access the global
variable.
3 The local variable is created when The global remains throughout the
the function(in which it is defined) entire program execution.
starts executing and it is destroyed
when the execution is complete.

4. It is preferred as local variables are It is generally not preferred as any


more reliable. Because the values function can change the values of
cannot be changed outside the global variable.
function.
Practice the following programs
 Python program to find the maximum of three
numbers using functions.
 Python program to swap 2 numbers using function.
 Python program to calculate simple interest using
function.
 Python program to find out the factorial of a given
number using function.
Modules in Python
Module

A module is a file consisting of Python code.


A module can define functions, classes and variables.
There are 2 types of Module:-
 User Defined Module
 Built in Module
What is a Module
Consider a module to be the same as a code library.
A file containing a set of functions you want to
include in your application.

Basically modules in python are .py files in which set


of functions are written.

Modules are imported using import command.


User Defined Module
Writing Modules
Every Python program is a module. That means every file that we save using .py extension
is a module.
Steps that illustrate how to create a module:-

Step1:- Create a file having extension .py


msg.py
def fun(a):
print("welcome",a)
Step2: Now open the python shell and import the above module and then call the
functionality present in that module.
>>> import msg
>>> msg.fun("Python")
welcome Python
>>>
Step3: We can also call the above created msg module in some another file. For that
purpose, open some another file and write the code in it as follows:-
msg1.py
import msg
msg.fun("TYCO")
Step4: Run the msg1.py program and will get the output:-
>>>
welcome TYCO
>>>
Writing Modules
# A simple module, modules.py
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
O/P:-
>>> import modules
>>> add(2,13)
15
Importing Objects from Modules
 When we simply use import statement, then we
can use any variable or function present within the
module.

 When use from….import statement, then we can


use only selected variables or functions within the
module.
The from import Statement

Python’s from statement lets you import specific


attributes from a module.
The from .. import .. has the following syntax :

O/P:-
>>> from modules import add
>>> add(2,3)
5
Programs

 Write a module for displaying the Fibonacci series.

 Write a python program to define a module for


swapping the two values.
Python Built-in Modules

Numbers and Numeric Representation

These functions are used to represent numbers in different forms.

The methods are like below:-


Sr.No. Function & Description

1 ceil(x)
Return the Ceiling value. It is the smallest integer, greater or equal to the number x.

2 factorial(x)
Returns factorial of x. where x ≥ 0

3 floor(x)
Return the Floor value. It is the largest integer, less or equal to the number x.

4 fsum(iterable)

Find sum of the elements in an iterable object

5 gcd(x, y)

Returns the Greatest Common Divisor of x and y

6 isfinite(x)

Checks whether x is neither an infinity nor nan.

7 isinf(x)

Checks whether x is infinity

8 isnan(x)

Checks whether x is not a number.

9 remainder(x, y)
Find remainder after dividing x by y.
For example:-
>>> import math
>>> math.ceil(2.3)
3
>>> math.factorial(3)
6
>>> math.pi
3.141592653589793
>>>
Namespaces
A namespace is a simple system to control the names in a
program. It ensures that names are unique and won’t lead to any
conflict.
Also, add to your knowledge that Python implements
namespaces in the form of dictionaries.
It maintains a name-to-object mapping where names act as keys
and the objects as values.
Multiple namespaces may have the same name but pointing to a
different variable.
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. It remains active until the function returns.
 Global Namespace
This namespace covers the names from various imported
modules used in a project. Python creates this namespace
for every module included in your program. It’ll last until
the program ends.
 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 you exit.
Scope
A variable is only available from inside the region it is created.
This is called scope.
 Local Scope
A variable created inside a function belongs to
the local scope of that function, and can only be used
inside that function.

Example:-
def myfunc():
x = 300
print(x)

myfunc()
 Global Scope
 A variable created in the main body of the Python code is a
global variable and belongs to the global scope.
 Global variables are available from within any scope,
global and local.

Example:-
x = 300

def myfunc():
print(x)

myfunc()

print(x)
 Naming Variables
 If you operate with the same variable name inside and outside
of a function, Python will treat them as two separate variables,
one available in the global scope (outside the function) and one
available in the local scope (inside the function):
Example:-
x = 300

def myfunc():
x = 200
print(x)

myfunc()

print(x)
Packages
Differences Between Python Modules and Packages

 A module is a file containing Python code. A package,


is like a directory that holds sub-packages and modules.
 A package must hold the file __init__.py. This does not
apply to modules.
 To import everything from a module, we use the
wildcard *. But this does not work with packages .
Introduction
 A package is a collection of Python Modules.
 A package is a hierarchical file directory structure that
defines a single python application environment that
consists of modules and sub-packages and
subsubpackages and so on.
 Packages allow for hierarchical structuring of the module
namespace using dot notation.
 Packages are a way of structuring many packages and
modules which help in a well-organized hierarchy of data
set, making the directories and modules easy to access.
Built-in Packages

Python provides many well-known built-in packages


like
 Math,
 Numpy,
 Scipy,
 Matplotlib,
 Pandas etc.
Built-in Package
Numpy Package

 NumPy is a general-purpose array-processing


package. It provides a high-performance
multidimensional array object, and tools for working
with these arrays.
 It is the fundamental package for scientific computing
with Python.
Advantages:-
o Array Oriented Computing
o Efficiently implemented multidimensional array
o Designed for scientific computation
how to use arrays using Numpy Package
>>>import numpy
>>> import numpy as np
>>> a=np.array([1,2,3])
>>> print(a)

O/P:-
[1,2,3]
>>>
Screenshot
Python program using Numpy package
SciPy(Scientific Library for Python) Package
 SciPy is a collection of mathematical algorithms and
convenience functions built on the NumPy extension
of Python.
 SciPy is an open source Python based library, which is
used in mathematics, scientific computing, Engineering
and technical computing.
 SciPy also pronounced as “Sigh Pi”.
 SciPy is a fully featured versions of Linear Algebra
while Numpy contains only a few features.
 Most new Data Science features are available in SciPy
rather than Numpy.
Screenshot using SciPy package
Matplotlib Package
 Matplotlib is a plotting library for the Python
Programming language and its numerical
mathematics extension NumPy.
 Matplotlib consists of several plots like line,
bar,scatter,histogram etc.
 We have to import the pyplot module of matplotlib
library under the alias plt.
 With the help of plot function we can start preparing
data for plotting and finally with the help of show
function we can display the drawing on the screen.
Python program to plot the bar graph using
Matplotlib package
Output of Bar graph using
Matplotlib
Python Program to plot a
line using Matplotlib package
Output to plot a line
Python program to plot the parabola
Output:-
Panda Package
 Pandas is a Python package providing fast, flexible and expressive data structures
designed to make working with structured(tabular, multidimensional, potentially
heterogeneous) and time series data.
 Pandas is well suited for many different kinds of data:-
o Tabular data with heterogeneously-typed columns, as in an SQL table or Excel
spreadsheet.
o Ordered and unordered(not necessarily fixed-frequency) time series data.
o Arbitrary matrix data(homogeneously typed or hetergeneous) with row and column
labels.
o Any other form of observational/statistical data sets. The data actually need not be
labeled at all to be placed into a pandas data structure.
o There are three data structures used in Panda—

 Series
 Data Frame
 Panel

o Series----It is a one dimensional homogeneous array. The size of this array is


immutable.

o
Python program using series and Data frame data
structure in Panda Package
User Define Package

 Decide about basic structure of package.


 Create the directory structure having folders with
name of package and sub package and so on.
 Create __init__.py file in a package and sub package
folder.
 The __init__.py file is normally kept empty.
 The Python interpreter recognizes a folder as the
package if it contains __init__.py file.
Importing Python Libraries

 To import module, write import command

 Use its function by giving its full name


 Example:-
Package_name.module_name.function(argument list)
Structure of our package

Package

Area.py Volume.py Modules

Rectangle()
Triangle() Cube()
Cuboid()
The End

You might also like