SlideShare a Scribd company logo
BCS-DS-427B: PYTHON
Ms. Swati Hans
Assistant Professor, CSE
Manav Rachna International Institute of Research and Studies, Faridabad
1
BCS-DS-427B: PYTHON
Functions
Ms. Swati Hans
Assistant Professor, CSE
MRIIRS
2
Python - Functions
• A function is a block of organized, reusable code that is used to
perform a single, related action. Functions provides better modularity
for your application and a high degree of code reusing.
• As you already know, Python gives you many built-in functions like
print() etc. but you can also create your own functions. These functions
are called user-defined functions.
Defining a Function
Here are simple rules to define a function in Python:
• Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these
parentheses.
• The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
• The code block within every function starts with a colon (:) and is
indented.
• 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.
• Syntax:
• def functionname( parameters ):
• "function_docstring" function_suite return [expression]
• Syntax:
def functionname( parameters ):
"function_docstring”
function_code
return [expression]
By default, parameters have a positional behavior, and you need
to inform them in the same order that they were defined.
• Example:
def printme( str ):
“creating first function”
print("This prints a passed string function“)
print (str)
Printme(“Happy Programming!”)
Calling a Function without argument
• Following is the example to call printme() function:
def print():
“creating second function to display msg”
print(“Hello world”);
print()
print();
• This would produce following result:
Hello world
Hello world
Here function print() is called without arguments .
This function is called twice so displays Hello world
twice.
Calling a Function with argument i.e
Pass by reference
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. For
example:
Program to add two numbers using function with arguments
def add(a,b):
sum=a+b
print sum
add(2,3) # calling add with two arguments 2,3 will print 5
add(4,5) # calling add with two arguments 4,5 will print 9
Calling a Function with argument
Program to swap two numbers using function with arguments
def swap(a,b):
temp=a
a=b
b=temp
x=2
y=3
print(“before swap x=“,x,”y=“,y)
swap(x,y) # swaping two numbers using pass byreference
print(“after swap x=“,x,”y=“,y)
====Output=====
before swap x=2 y=3
after swap x=3 y=2
Passing List to function
def changeme( mylist ):
#This function changes a passed list
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
• So this would produce following result:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference but
inside the function, but the reference is being over-written.
def changeme( mylist ): "This changes a passed list"
mylist = [1,2,3,4];
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
• The parameter mylist is local to the function changeme. Changing mylist
within the function does not affect mylist. The function accomplishes
nothing and finally this would produce following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function returning value
 A return statement is used to end the execution of the function
call and “returns” the result (value of the expression following
the return keyword) to the caller.
 The statements after the return statements are not executed. If
the return statement is without any expression, then the special
value None is returned.
 A return statement is overall used to invoke a function so that
the passed statements can be executed.
 Note: Return statement can not be used outside the function.
Syntax:
def functionname(parameters):
statements
.
.
return [expression]
Function returning value Example
Function to find cube of a number and return value of
cube
def cube(x):
r=x**3
return r
val=cube(3)
#calls function and pass 3
#function returns value and store in val
print(“cube is”,value)
Output
Cube is 27
Function returning value Example
Program to find factorial of a number using function
returning value
def factorial(x):
fact=1
for i in range(1,x+1):
fact=fact*I
return fact
num=4
f=factorial(num)
print(“factorial of”,num,” is”,f)
Function returning Multiple values
In Python, we can return multiple values from a function
def getdata():
name = “Rahi"
rollno= 20
return rollno,name;
# call function
n,r = getdata()
print(“name=“,n)
print(“rollno=“,r)
Function Arguments:
A function by using the following types of formal arguments::
– Positional arguments
– Keyword arguments
– Default arguments
– Variable-length arguments
Positional arguments:
– The list of variables declared in the parentheses at the time of
defining a function are the formal arguments. And, these arguments
are also known as positional arguments. A function may be defined
with any number of formal arguments.
– While calling a function −
– All the arguments are required.
– The number of actual arguments must be equal to the number of
formal arguments.
– They Pick up values in the order of definition.
Positional arguments Example
def add(x,y):
z = x+y
print (z)
a = 10
b = 20
add(a, b)
It will produce the following output −
x=10 y=20 x+y=30
Here, the add() function has two formal arguments, both are
numeric.
When integers 10 and 20 passed to it. The variable "a" takes 10
and "b" takes 20, in the order of declaration. The add() function
displays the addition.
Keyword arguments:
• Keyword arguments are related to the function calls. When you
use keyword arguments in a function call, the caller identifies
the arguments by the parameter name.
• This allows you 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.
def printinfo( name, age ):
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function by positional
arguments
printinfo ("Naveen", 29)
# by keyword arguments
printinfo(name="miki", age = 30)
printinfo(age=40,name=“Raghav”)
Following example gives more clear picture. Note, here order of
the parameter does not matter:
def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
printinfo( age=40, name=“Raghav" );
• This would produce following result:
Name: Raghav Age 40
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.
• Following example gives idea on default arguments, it would
print default age if it is not passed:
def printinfo( name, age = 35 ): “Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
• This would produce following result:
Name: miki Age 50 Name: miki Age 35
Variable-length arguments:
• You may need to process a function for more arguments than
you specified while defining the function. These arguments are
called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
• The general syntax for a function with non-keyword variable
arguments is this:
def functionname([formal_args,] *args_tuple ):
function_code
return [expression]
• An asterisk (*) is placed before the variable name that will hold
the values of all nonkeyword variable arguments. This tuple
remains empty if no additional arguments are specified during
the function call. For example:
def printinfo(*argstuple ):
print(“in function”)
for var in vartuple:
print var
printinfo();
printinfo( 70, 60, 50 );
• This would produce following result:
Output is:
In function
Output is:
In function
70
60
50
The Anonymous Functions:
You can use the lambda keyword to create small anonymous functions.
These functions are called anonymous because they are not declared
in the standard manner by using the def keyword.
• Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands or
multiple expressions.
• An anonymous function cannot be a direct call to print because
lambda requires an expression.
• Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the
global namespace.
• Although it appears that lambda's are a one-line version of a function,
they are not equivalent to inline statements in C or C++, whose
purpose is by passing function stack allocation during invocation for
performance reasons.
• Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example:
• Following is the example to show how lembda form of function
works:
sum = lambda arg1, arg2: arg1 + arg2;
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
• This would produce following result:
Value of total : 30
Value of total : 40
Scope of Variables:
• All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
• The scope of a variable determines the portion of the program where
you can access a particular identifier. There are two basic scopes of
variables in Python:
Global variables
Local variables
• 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. When you call
a function, the variables declared inside it are brought into scope.
• Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ): # arg1 and arg2 are local
variables
total = arg1 + arg2;
print "Inside the function local total : ", total
# Now call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
• This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
Note:
1.Scope of local variables is within function
2.Scope of global variables is outside function also.
Questions
• Create function to find whether number is
prime or not using function with argument
• Create a function to find area of circle
• Create a function to return area and
perimeter of cube
Ad

More Related Content

Similar to functions _ (20)

JNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptxJNTUK python programming python unit 3.pptx
JNTUK python programming python unit 3.pptx
Venkateswara Babu Ravipati
 
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
Function in Python.pptx by Faculty at gla university in mathura uttar pradeshFunction in Python.pptx by Faculty at gla university in mathura uttar pradesh
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
bloodskullgoswami
 
Functions
FunctionsFunctions
Functions
Golda Margret Sheeba J
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
Mohammad Hassan
 
Function oneshot with python programming .pptx
Function oneshot with python programming .pptxFunction oneshot with python programming .pptx
Function oneshot with python programming .pptx
lionsconvent1234
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of PythonLearn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
ArshiniGubbala3
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Function
Function Function
Function
Kathmandu University
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Functions
FunctionsFunctions
Functions
PralhadKhanal1
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
KrithikaTM
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Decided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the numberDecided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the number
harshoberoi2050
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and oppfunctions notes.pdf python functions and opp
functions notes.pdf python functions and opp
KirtiGarg71
 
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
Function in Python.pptx by Faculty at gla university in mathura uttar pradeshFunction in Python.pptx by Faculty at gla university in mathura uttar pradesh
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
bloodskullgoswami
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
zueZ3
 
Function oneshot with python programming .pptx
Function oneshot with python programming .pptxFunction oneshot with python programming .pptx
Function oneshot with python programming .pptx
lionsconvent1234
 
Learn more about the concepts Functions of Python
Learn more about the concepts Functions of PythonLearn more about the concepts Functions of Python
Learn more about the concepts Functions of Python
PrathamKandari
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
KrithikaTM
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Decided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the numberDecided to go to the 65 and the value of the number
Decided to go to the 65 and the value of the number
harshoberoi2050
 
functions notes.pdf python functions and opp
functions notes.pdf python functions and oppfunctions notes.pdf python functions and opp
functions notes.pdf python functions and opp
KirtiGarg71
 

More from SwatiHans10 (20)

ip addressing _
ip addressing                               _ip addressing                               _
ip addressing _
SwatiHans10
 
stop and wait _
stop and wait                            _stop and wait                            _
stop and wait _
SwatiHans10
 
subnetting _
subnetting                                  _subnetting                                  _
subnetting _
SwatiHans10
 
PipelineHazards _
PipelineHazards                                    _PipelineHazards                                    _
PipelineHazards _
SwatiHans10
 
Pipelining _
Pipelining                                               _Pipelining                                               _
Pipelining _
SwatiHans10
 
Mobile Customer Experience Management.pptx
Mobile Customer Experience Management.pptxMobile Customer Experience Management.pptx
Mobile Customer Experience Management.pptx
SwatiHans10
 
Social Web multimedia analytics goals _
Social Web multimedia analytics goals            _Social Web multimedia analytics goals            _
Social Web multimedia analytics goals _
SwatiHans10
 
Hardwires and Microprogrammed Control ,
Hardwires and Microprogrammed Control                   ,Hardwires and Microprogrammed Control                   ,
Hardwires and Microprogrammed Control ,
SwatiHans10
 
Restoring Algorithm _
Restoring Algorithm                      _Restoring Algorithm                      _
Restoring Algorithm _
SwatiHans10
 
Non -Restoring Algorithm _
Non -Restoring Algorithm                   _Non -Restoring Algorithm                   _
Non -Restoring Algorithm _
SwatiHans10
 
Instruction execution cycle _
Instruction execution cycle                  _Instruction execution cycle                  _
Instruction execution cycle _
SwatiHans10
 
RTL,Instruction set _
RTL,Instruction set                                  _RTL,Instruction set                                  _
RTL,Instruction set _
SwatiHans10
 
Data representation _
Data representation                        _Data representation                        _
Data representation _
SwatiHans10
 
CAO PPT-Lect 1 _
CAO PPT-Lect 1                                    _CAO PPT-Lect 1                                    _
CAO PPT-Lect 1 _
SwatiHans10
 
CIRCULAR LINKED LIST _
CIRCULAR LINKED LIST                       _CIRCULAR LINKED LIST                       _
CIRCULAR LINKED LIST _
SwatiHans10
 
Transmission control protocol _
Transmission control protocol            _Transmission control protocol            _
Transmission control protocol _
SwatiHans10
 
Lecture 1 .
Lecture 1                                     .Lecture 1                                     .
Lecture 1 .
SwatiHans10
 
PipelineHazards _
PipelineHazards                                    _PipelineHazards                                    _
PipelineHazards _
SwatiHans10
 
Mobile Customer Experience Management.pptx
Mobile Customer Experience Management.pptxMobile Customer Experience Management.pptx
Mobile Customer Experience Management.pptx
SwatiHans10
 
Social Web multimedia analytics goals _
Social Web multimedia analytics goals            _Social Web multimedia analytics goals            _
Social Web multimedia analytics goals _
SwatiHans10
 
Hardwires and Microprogrammed Control ,
Hardwires and Microprogrammed Control                   ,Hardwires and Microprogrammed Control                   ,
Hardwires and Microprogrammed Control ,
SwatiHans10
 
Restoring Algorithm _
Restoring Algorithm                      _Restoring Algorithm                      _
Restoring Algorithm _
SwatiHans10
 
Non -Restoring Algorithm _
Non -Restoring Algorithm                   _Non -Restoring Algorithm                   _
Non -Restoring Algorithm _
SwatiHans10
 
Instruction execution cycle _
Instruction execution cycle                  _Instruction execution cycle                  _
Instruction execution cycle _
SwatiHans10
 
RTL,Instruction set _
RTL,Instruction set                                  _RTL,Instruction set                                  _
RTL,Instruction set _
SwatiHans10
 
Data representation _
Data representation                        _Data representation                        _
Data representation _
SwatiHans10
 
CAO PPT-Lect 1 _
CAO PPT-Lect 1                                    _CAO PPT-Lect 1                                    _
CAO PPT-Lect 1 _
SwatiHans10
 
CIRCULAR LINKED LIST _
CIRCULAR LINKED LIST                       _CIRCULAR LINKED LIST                       _
CIRCULAR LINKED LIST _
SwatiHans10
 
Transmission control protocol _
Transmission control protocol            _Transmission control protocol            _
Transmission control protocol _
SwatiHans10
 
Ad

Recently uploaded (20)

DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Machine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptxMachine learning project on employee attrition detection using (2).pptx
Machine learning project on employee attrition detection using (2).pptx
rajeswari89780
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
Reagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptxReagent dosing (Bredel) presentation.pptx
Reagent dosing (Bredel) presentation.pptx
AlejandroOdio
 
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E..."Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
"Boiler Feed Pump (BFP): Working, Applications, Advantages, and Limitations E...
Infopitaara
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
IntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdfIntroSlides-April-BuildWithAI-VertexAI.pdf
IntroSlides-April-BuildWithAI-VertexAI.pdf
Luiz Carneiro
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)QA/QC Manager (Quality management Expert)
QA/QC Manager (Quality management Expert)
rccbatchplant
 
Ad

functions _

  • 1. BCS-DS-427B: PYTHON Ms. Swati Hans Assistant Professor, CSE Manav Rachna International Institute of Research and Studies, Faridabad 1
  • 2. BCS-DS-427B: PYTHON Functions Ms. Swati Hans Assistant Professor, CSE MRIIRS 2
  • 3. Python - Functions • A function is a block of organized, reusable code that is used to perform a single, related action. Functions provides better modularity for your application and a high degree of code reusing. • As you already know, Python gives you many built-in functions like print() etc. but you can also create your own functions. These functions are called user-defined functions.
  • 4. Defining a Function Here are simple rules to define a function in Python: • Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). • Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. • The first statement of a function can be an optional statement - the documentation string of the function or docstring. • The code block within every function starts with a colon (:) and is indented. • 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. • Syntax: • def functionname( parameters ): • "function_docstring" function_suite return [expression]
  • 5. • Syntax: def functionname( parameters ): "function_docstring” function_code return [expression] By default, parameters have a positional behavior, and you need to inform them in the same order that they were defined. • Example: def printme( str ): “creating first function” print("This prints a passed string function“) print (str) Printme(“Happy Programming!”)
  • 6. Calling a Function without argument • Following is the example to call printme() function: def print(): “creating second function to display msg” print(“Hello world”); print() print(); • This would produce following result: Hello world Hello world Here function print() is called without arguments . This function is called twice so displays Hello world twice.
  • 7. Calling a Function with argument i.e Pass by reference 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. For example: Program to add two numbers using function with arguments def add(a,b): sum=a+b print sum add(2,3) # calling add with two arguments 2,3 will print 5 add(4,5) # calling add with two arguments 4,5 will print 9
  • 8. Calling a Function with argument Program to swap two numbers using function with arguments def swap(a,b): temp=a a=b b=temp x=2 y=3 print(“before swap x=“,x,”y=“,y) swap(x,y) # swaping two numbers using pass byreference print(“after swap x=“,x,”y=“,y) ====Output===== before swap x=2 y=3 after swap x=3 y=2
  • 9. Passing List to function def changeme( mylist ): #This function changes a passed list mylist.append([1,2,3,4]); print "Values inside the function: ", mylist mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist • So this would produce following result: Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
  • 10. There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written. def changeme( mylist ): "This changes a passed list" mylist = [1,2,3,4]; print "Values inside the function: ", mylist return mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist • The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce following result: Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]
  • 11. Function returning value  A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller.  The statements after the return statements are not executed. If the return statement is without any expression, then the special value None is returned.  A return statement is overall used to invoke a function so that the passed statements can be executed.  Note: Return statement can not be used outside the function. Syntax: def functionname(parameters): statements . . return [expression]
  • 12. Function returning value Example Function to find cube of a number and return value of cube def cube(x): r=x**3 return r val=cube(3) #calls function and pass 3 #function returns value and store in val print(“cube is”,value) Output Cube is 27
  • 13. Function returning value Example Program to find factorial of a number using function returning value def factorial(x): fact=1 for i in range(1,x+1): fact=fact*I return fact num=4 f=factorial(num) print(“factorial of”,num,” is”,f)
  • 14. Function returning Multiple values In Python, we can return multiple values from a function def getdata(): name = “Rahi" rollno= 20 return rollno,name; # call function n,r = getdata() print(“name=“,n) print(“rollno=“,r)
  • 15. Function Arguments: A function by using the following types of formal arguments:: – Positional arguments – Keyword arguments – Default arguments – Variable-length arguments Positional arguments: – The list of variables declared in the parentheses at the time of defining a function are the formal arguments. And, these arguments are also known as positional arguments. A function may be defined with any number of formal arguments. – While calling a function − – All the arguments are required. – The number of actual arguments must be equal to the number of formal arguments. – They Pick up values in the order of definition.
  • 16. Positional arguments Example def add(x,y): z = x+y print (z) a = 10 b = 20 add(a, b) It will produce the following output − x=10 y=20 x+y=30 Here, the add() function has two formal arguments, both are numeric. When integers 10 and 20 passed to it. The variable "a" takes 10 and "b" takes 20, in the order of declaration. The add() function displays the addition.
  • 17. Keyword arguments: • Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. • This allows you 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. def printinfo( name, age ): print ("Name: ", name) print ("Age ", age) return # Now you can call printinfo function by positional arguments printinfo ("Naveen", 29) # by keyword arguments printinfo(name="miki", age = 30) printinfo(age=40,name=“Raghav”)
  • 18. Following example gives more clear picture. Note, here order of the parameter does not matter: def printinfo( name, age ): "Test function" print "Name: ", name; print "Age ", age; printinfo( age=40, name=“Raghav" ); • This would produce following result: Name: Raghav Age 40
  • 19. 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. • Following example gives idea on default arguments, it would print default age if it is not passed: def printinfo( name, age = 35 ): “Test function" print "Name: ", name; print "Age ", age; return; printinfo( age=50, name="miki" ); printinfo( name="miki" ); • This would produce following result: Name: miki Age 50 Name: miki Age 35
  • 20. Variable-length arguments: • You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. • The general syntax for a function with non-keyword variable arguments is this: def functionname([formal_args,] *args_tuple ): function_code return [expression]
  • 21. • An asterisk (*) is placed before the variable name that will hold the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. For example: def printinfo(*argstuple ): print(“in function”) for var in vartuple: print var printinfo(); printinfo( 70, 60, 50 ); • This would produce following result: Output is: In function Output is: In function 70 60 50
  • 22. The Anonymous Functions: You can use the lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard manner by using the def keyword. • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. • An anonymous function cannot be a direct call to print because lambda requires an expression. • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. • Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons. • Syntax: lambda [arg1 [,arg2,.....argn]]:expression
  • 23. Example: • Following is the example to show how lembda form of function works: sum = lambda arg1, arg2: arg1 + arg2; print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) • This would produce following result: Value of total : 30 Value of total : 40
  • 24. Scope of Variables: • All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. • The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python: Global variables Local variables • 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. When you call a function, the variables declared inside it are brought into scope.
  • 25. • Example: total = 0; # This is global variable. def sum( arg1, arg2 ): # arg1 and arg2 are local variables total = arg1 + arg2; print "Inside the function local total : ", total # Now call sum function sum( 10, 20 ); print "Outside the function global total : ", total • This would produce following result: Inside the function local total : 30 Outside the function global total : 0 Note: 1.Scope of local variables is within function 2.Scope of global variables is outside function also.
  • 26. Questions • Create function to find whether number is prime or not using function with argument • Create a function to find area of circle • Create a function to return area and perimeter of cube