SlideShare a Scribd company logo
© Amir Kirsh
MACHINE LEARNING WITH PYTHON
UNIT II
What Are Functions?
Functions are the structured or procedural programming way of
organizing the logic in the programs.
Functions can appear in different ways… here is a sampling profile
of how you will see functions created, used, or otherwise
referenced:
• declaration/definition
def foo():
print( 'bar‘)
• function object/reference foo
• function call/invocation foo()
Functions vs. Procedures
Functions are often compared to procedures. Both are entities
which can be invoked, but the traditional function or "black box,"
perhaps taking some or no input parameters, performs some
amount of processing and concludes by sending back a return
value to the caller.
Some functions are Boolean in nature, returning a "yes" or "no"
answer, or, more appropriately, a non-zero or zero value.
Procedures, often compared to functions, are simply special cases,
functions which do not return a value.
Python procedures are implied functions because the interpreter
implicitly returns a default value of None.
Return Values and Function Types
Functions may return a value back to its caller and those which are
more procedural in nature do not explicitly return anything at all.
Languages which treat procedures as functions usually have a
special type or value name for functions that "return nothing.“
The hello() function acts as a procedure and returning no value. If
the return value is saved, then its value is None:
>>> def hello():
… print 'hello world'
>>>
Return Values and Function Types
>>> res = hello()
hello world
>>> res
>>> print res
None
>>> type(res)
<type 'None'>
Return Values and Function Types
Like most languages, python also return only one value/object from
a function. One difference is that in returning a container type, it will
actually return more than a single object.
def foo():
return ['xyz', 1000000, -98.6]
def bar():
return 'abc', [42, 'python‘], "Guido“]
def bar():
return ('abc', [4-2j, 'python'], "Guido")
Return Values and Function Types
As far as return values are concerned, tuples can be saved in a
number of ways.
>>> aTuple = bar()
>>> x, y, z = bar()
>>> (a, b, c) = bar()
>>> aTuple
('abc', [(4-2j), 'python'], 'Guido')
>>> x, y, z
('abc', [(4-2j), 'python'], 'Guido')
>>> (a, b, c)
('abc', [(4-2j), 'python'], 'Guido')
Calling Functions
Functions are called using the same pair of parentheses that are
used to. In fact, some consider ( ( ) ) to be a two-character
operator, the function operator.
Any input parameters or arguments must be placed between these
calling parentheses.
Parentheses are also used as part of function declarations to define
those arguments.
Calling Functions
def foo(x):
foo_suite (OR) foo_body
def foo():
print()
print()
x=a+b
return x
foo(x=42)
foo('bar')
foo(y)
Keyword Arguments
The concept of keyword arguments applies only to function
invocation. The idea here is for the caller to identify the arguments
by parameter name in a function call. This specification
allows for arguments to be missing or out-of-order because the
interpreter is able to use the provided keywords to match values to
parameters.
Keyword Arguments
foo(who=“rajesh”)
foo(x='bar')
foo(x=y)
Default Arguments
Default arguments are those which are declared with default
values. Parameters which are not passed on a function call are
thus allowed and are assigned the default value.
>>> def taxMe(cost, rate=0.0825):
… return cost + (cost * rate)
…
>>> taxMe(100)
108.25
>>>>>> taxMe(100, 0.05)
105.0
Creating Functions
def Statement
Functions are created using the def statement, with a syntax
def function_name(arguments):
"function_documentation_string"
function_body_suite
The header line consists of the def keyword, the function name,
and a set of arguments (if any).
The remainder of the def clause consists of an optional but
highly-recommended documentation string and the required
function body suite.
Creating Functions
def Statement
Functions are created using the def statement, with a syntax
def function_name(arguments):
"function_documentation_string"
function_body_suite
The header line consists of the def keyword, the function name,
and a set of arguments (if any).
The remainder of the def clause consists of an optional but
highly-recommended documentation string and the required
function body suite.
Creating Functions - Example
def helloSomeone(who):
'returns a salutory string customized with the input'
return "Hello" + str(who)
helloSomeone(‘Mehdi’)
Passing Functions
In Python, functions are just like any other object. They can be
referenced (accessed or aliased to other variables), passed as
arguments to functions, be elements of container objects like lists
and dictionaries, etc.
The one unique characteristic of functions which may set them
apart from other objects is that they are callable, i.e., can be
invoked via the function operator.
Passing Functions
def bar():
print 'in bar()'
def foo():
print 'in foo()'
bar()
Passing Functions
Functions can be aliases to other variables. Because all objects are
passed by reference, functions are no different. When assigning to
another variable, i.e. assigning the reference to the same object;
and if that object is a function, then all aliases to that same object
are invokable:
>>> def foo():
… print('in foo()‘)
…
>>> bar = foo
>>> bar()
in foo()
Passing Functions
One can even pass functions in as arguments to other functions for
invocation:
Example:
def bar(foo):
foo()
def foo():
print('in foo()')
bar(foo)
Formal Arguments
A Python function's set of formal arguments consists of all
parameters passed to the function on invocation for which there is
an exact correspondence to those of the argument list in the
function declaration.
These arguments include all required arguments (passed to the
function in correct positional order), keyword arguments (passed
in- or out-of-order, but which have keywords present to match their
values to their proper positions in the argument list), and all
arguments which have default values which may or may not be part
of the function call.
Positional Arguments
Positional arguments must be passed in the exact order that they
are defined for the functions that are called.
Also, without the presence of any default arguments, the exact
number of arguments passed to a function (call) must be exactly
the number declared
Positional Arguments- Example
>>> def foo(who): # defined for only 1 argument
… print 'Hello', who
…
>>> foo() # 0 arguments… BAD
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: not enough arguments; expected 1, got 0
>>> foo('World!') # 1 argument… WORKS
Hello World!
>>> foo('Mr.', 'World!')# 2 arguments… BAD
Traceback (innermost last):
File "<stdin>", line 1, in ?
TypeError: too many arguments; expected 1, got 2
Variable-length Arguments
There may be situations where a function is required to process an unknown
number of arguments. These are called variable-length argument lists.
Variable-length arguments are not named explicitly in function declarations
because the number of arguments is unknown before run-time (and even during
execution, the number of arguments may be different on successive calls), an
obvious difference from formal arguments (positional and default) which are
named in function declarations.
Python supports variable-length arguments in two ways because function calls
provide for both keyword and non-keyword argument types.
Non-keyword Variable Arguments (Tuple)
When a function is invoked, all formal (required and default) arguments are
assigned to their corresponding local variables as given in the function
declaration. The remaining non-keyword variable arguments are inserted in
order into a tuple for access.
def function_name([formal_args,]*vargs_tuple):
"function_documentation_string"
function_body_suite
Non-keyword Variable Arguments (Tuple)
def tupleVarArgs(arg1, arg2='defaultB', *theRest):
‘ display regular args and non-keyword variable args'
print 'formal arg 1:', arg1
print 'formal arg 2:', arg1
for eachXtrArg in theRest:
print 'another arg:', eachXtrArg
Non-keyword Variable Arguments (Tuple)
>>> tupleVarArgs('abc')
formal arg 1: abc
formal arg 2: defaultB
>>> tupleVarArgs(23, 4.56)
formal arg 1: 23
formal arg 2: 4.56
>>> tupleVarArgs('abc', 123, 'xyz', 456.789)
formal arg 1: abc
formal arg 2: 123
another arg: xyz
another arg: 456.789
Keyword Variable Arguments (Dictionary)
In the case where we have a variable number or extra set of keyword arguments,
these are placed into a dictionary where the "keyworded" argument variable
names are the keys, and the arguments are their corresponding values.
def function_name([formal_args,][*vargst,] **vargsd):
function_documentation_string
function_body_suite
To differentiate keyword variable arguments from non-keyword informal
arguments, a double asterisk ( ** ) is used. The ** is overloaded so it should not
be confused with exponentiation. The keyword variable argument dictionary
should be the last parameter of the function definition prepended with the '**'.
Keyword Variable Arguments (Dictionary)
def dictVarArgs(arg1, arg2='defaultB', **theRest):
‘ display 2 regular args and keyword variable args'
print ('formal arg1:', dictVarArgs)
print( 'formal arg2:', arg2)
for eachXtrArg in theRest.keys():
print 'Xtra arg %s: %s' % 
(eachXtrArg, str(theRest[eachXtrArg]))
Keyword Variable Arguments (Dictionary)
>>> dictVarArgs(1220, 740.0, c='grail‘)
formal arg1: 1220
formal arg2: 740.0
Xtra arg c: grail
>>> dictVarArgs('one', d=10, e='zoo',
men=('freud', 'gaudi'))
formal arg1: one
formal arg2: defaultB
Xtra arg men: ('freud', 'gaudi')
Xtra arg d: 10
Xtra arg e: zoo
Keyword Variable Arguments (Dictionary)
>>> dictVarArgs(1220, 740.0, c='grail‘)
formal arg1: 1220
formal arg2: 740.0
Xtra arg c: grail
>>> dictVarArgs('one', d=10, e='zoo',
men=('freud', 'gaudi'))
formal arg1: one
formal arg2: defaultB
Xtra arg men: ('freud', 'gaudi')
Xtra arg d: 10
Xtra arg e: zoo
Ad

More Related Content

Similar to Functions in Python with all type of arguments (20)

Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.pptPy-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python FunctionsPowerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
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
 
Python basic
Python basicPython basic
Python basic
Saifuddin Kaijar
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12
Vishal Dutt
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
MalligaarjunanN
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 
Lecture 08.pptx
Lecture 08.pptxLecture 08.pptx
Lecture 08.pptx
Mohammad Hassan
 
functions _
functions                                 _functions                                 _
functions _
SwatiHans10
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... Functions
Michal Bigos
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
Karthik Prakash
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.pptPy-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python FunctionsPowerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
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
 
Python functions part12
Python functions  part12Python functions  part12
Python functions part12
Vishal Dutt
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
MalligaarjunanN
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
Python Learn Function with example programs
Python Learn Function with example programsPython Learn Function with example programs
Python Learn Function with example programs
GeethaPanneer
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
prasnt1
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
All About ... Functions
All About ... FunctionsAll About ... Functions
All About ... Functions
Michal Bigos
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
Ashwini Raut
 

More from riazahamed37 (8)

Python Way of Program is a topic for beginners
Python Way of Program is a topic for beginnersPython Way of Program is a topic for beginners
Python Way of Program is a topic for beginners
riazahamed37
 
JTABBED PANE is a swing concept used to have tabs
JTABBED PANE is a swing concept used to have tabsJTABBED PANE is a swing concept used to have tabs
JTABBED PANE is a swing concept used to have tabs
riazahamed37
 
JCheckBox is a light weight component of java
JCheckBox is a light weight component of javaJCheckBox is a light weight component of java
JCheckBox is a light weight component of java
riazahamed37
 
This presentation is about swing concept in python
This presentation is about swing concept in pythonThis presentation is about swing concept in python
This presentation is about swing concept in python
riazahamed37
 
JTRee is a swing concept and it is said to be light weight component
JTRee is a swing concept and it is said to be light weight componentJTRee is a swing concept and it is said to be light weight component
JTRee is a swing concept and it is said to be light weight component
riazahamed37
 
Arrays a detailed explanation and presentation
Arrays a detailed explanation and presentationArrays a detailed explanation and presentation
Arrays a detailed explanation and presentation
riazahamed37
 
CONTROL FLOW STRUCTURE IN JAVA LANG.pdf
CONTROL FLOW  STRUCTURE IN JAVA LANG.pdfCONTROL FLOW  STRUCTURE IN JAVA LANG.pdf
CONTROL FLOW STRUCTURE IN JAVA LANG.pdf
riazahamed37
 
object oriented programming in javaTERNARY OPERATORS.pptx
object oriented programming in javaTERNARY OPERATORS.pptxobject oriented programming in javaTERNARY OPERATORS.pptx
object oriented programming in javaTERNARY OPERATORS.pptx
riazahamed37
 
Python Way of Program is a topic for beginners
Python Way of Program is a topic for beginnersPython Way of Program is a topic for beginners
Python Way of Program is a topic for beginners
riazahamed37
 
JTABBED PANE is a swing concept used to have tabs
JTABBED PANE is a swing concept used to have tabsJTABBED PANE is a swing concept used to have tabs
JTABBED PANE is a swing concept used to have tabs
riazahamed37
 
JCheckBox is a light weight component of java
JCheckBox is a light weight component of javaJCheckBox is a light weight component of java
JCheckBox is a light weight component of java
riazahamed37
 
This presentation is about swing concept in python
This presentation is about swing concept in pythonThis presentation is about swing concept in python
This presentation is about swing concept in python
riazahamed37
 
JTRee is a swing concept and it is said to be light weight component
JTRee is a swing concept and it is said to be light weight componentJTRee is a swing concept and it is said to be light weight component
JTRee is a swing concept and it is said to be light weight component
riazahamed37
 
Arrays a detailed explanation and presentation
Arrays a detailed explanation and presentationArrays a detailed explanation and presentation
Arrays a detailed explanation and presentation
riazahamed37
 
CONTROL FLOW STRUCTURE IN JAVA LANG.pdf
CONTROL FLOW  STRUCTURE IN JAVA LANG.pdfCONTROL FLOW  STRUCTURE IN JAVA LANG.pdf
CONTROL FLOW STRUCTURE IN JAVA LANG.pdf
riazahamed37
 
object oriented programming in javaTERNARY OPERATORS.pptx
object oriented programming in javaTERNARY OPERATORS.pptxobject oriented programming in javaTERNARY OPERATORS.pptx
object oriented programming in javaTERNARY OPERATORS.pptx
riazahamed37
 
Ad

Recently uploaded (20)

Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Unit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its typesUnit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its types
bharath321164
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Open Access: Revamping Library Learning Resources.
Open Access: Revamping Library Learning Resources.Open Access: Revamping Library Learning Resources.
Open Access: Revamping Library Learning Resources.
Rishi Bankim Chandra Evening College, Naihati, North 24 Parganas, West Bengal, India
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Timber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptxTimber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptx
Tantish QS, UTM
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-26-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-26-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-26-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-26-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Unit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its typesUnit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its types
bharath321164
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Timber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptxTimber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptx
Tantish QS, UTM
 
Ad

Functions in Python with all type of arguments

  • 1. © Amir Kirsh MACHINE LEARNING WITH PYTHON UNIT II
  • 2. What Are Functions? Functions are the structured or procedural programming way of organizing the logic in the programs. Functions can appear in different ways… here is a sampling profile of how you will see functions created, used, or otherwise referenced: • declaration/definition def foo(): print( 'bar‘) • function object/reference foo • function call/invocation foo()
  • 3. Functions vs. Procedures Functions are often compared to procedures. Both are entities which can be invoked, but the traditional function or "black box," perhaps taking some or no input parameters, performs some amount of processing and concludes by sending back a return value to the caller. Some functions are Boolean in nature, returning a "yes" or "no" answer, or, more appropriately, a non-zero or zero value. Procedures, often compared to functions, are simply special cases, functions which do not return a value. Python procedures are implied functions because the interpreter implicitly returns a default value of None.
  • 4. Return Values and Function Types Functions may return a value back to its caller and those which are more procedural in nature do not explicitly return anything at all. Languages which treat procedures as functions usually have a special type or value name for functions that "return nothing.“ The hello() function acts as a procedure and returning no value. If the return value is saved, then its value is None: >>> def hello(): … print 'hello world' >>>
  • 5. Return Values and Function Types >>> res = hello() hello world >>> res >>> print res None >>> type(res) <type 'None'>
  • 6. Return Values and Function Types Like most languages, python also return only one value/object from a function. One difference is that in returning a container type, it will actually return more than a single object. def foo(): return ['xyz', 1000000, -98.6] def bar(): return 'abc', [42, 'python‘], "Guido“] def bar(): return ('abc', [4-2j, 'python'], "Guido")
  • 7. Return Values and Function Types As far as return values are concerned, tuples can be saved in a number of ways. >>> aTuple = bar() >>> x, y, z = bar() >>> (a, b, c) = bar() >>> aTuple ('abc', [(4-2j), 'python'], 'Guido') >>> x, y, z ('abc', [(4-2j), 'python'], 'Guido') >>> (a, b, c) ('abc', [(4-2j), 'python'], 'Guido')
  • 8. Calling Functions Functions are called using the same pair of parentheses that are used to. In fact, some consider ( ( ) ) to be a two-character operator, the function operator. Any input parameters or arguments must be placed between these calling parentheses. Parentheses are also used as part of function declarations to define those arguments.
  • 9. Calling Functions def foo(x): foo_suite (OR) foo_body def foo(): print() print() x=a+b return x foo(x=42) foo('bar') foo(y)
  • 10. Keyword Arguments The concept of keyword arguments applies only to function invocation. The idea here is for the caller to identify the arguments by parameter name in a function call. This specification allows for arguments to be missing or out-of-order because the interpreter is able to use the provided keywords to match values to parameters.
  • 12. Default Arguments Default arguments are those which are declared with default values. Parameters which are not passed on a function call are thus allowed and are assigned the default value. >>> def taxMe(cost, rate=0.0825): … return cost + (cost * rate) … >>> taxMe(100) 108.25 >>>>>> taxMe(100, 0.05) 105.0
  • 13. Creating Functions def Statement Functions are created using the def statement, with a syntax def function_name(arguments): "function_documentation_string" function_body_suite The header line consists of the def keyword, the function name, and a set of arguments (if any). The remainder of the def clause consists of an optional but highly-recommended documentation string and the required function body suite.
  • 14. Creating Functions def Statement Functions are created using the def statement, with a syntax def function_name(arguments): "function_documentation_string" function_body_suite The header line consists of the def keyword, the function name, and a set of arguments (if any). The remainder of the def clause consists of an optional but highly-recommended documentation string and the required function body suite.
  • 15. Creating Functions - Example def helloSomeone(who): 'returns a salutory string customized with the input' return "Hello" + str(who) helloSomeone(‘Mehdi’)
  • 16. Passing Functions In Python, functions are just like any other object. They can be referenced (accessed or aliased to other variables), passed as arguments to functions, be elements of container objects like lists and dictionaries, etc. The one unique characteristic of functions which may set them apart from other objects is that they are callable, i.e., can be invoked via the function operator.
  • 17. Passing Functions def bar(): print 'in bar()' def foo(): print 'in foo()' bar()
  • 18. Passing Functions Functions can be aliases to other variables. Because all objects are passed by reference, functions are no different. When assigning to another variable, i.e. assigning the reference to the same object; and if that object is a function, then all aliases to that same object are invokable: >>> def foo(): … print('in foo()‘) … >>> bar = foo >>> bar() in foo()
  • 19. Passing Functions One can even pass functions in as arguments to other functions for invocation: Example: def bar(foo): foo() def foo(): print('in foo()') bar(foo)
  • 20. Formal Arguments A Python function's set of formal arguments consists of all parameters passed to the function on invocation for which there is an exact correspondence to those of the argument list in the function declaration. These arguments include all required arguments (passed to the function in correct positional order), keyword arguments (passed in- or out-of-order, but which have keywords present to match their values to their proper positions in the argument list), and all arguments which have default values which may or may not be part of the function call.
  • 21. Positional Arguments Positional arguments must be passed in the exact order that they are defined for the functions that are called. Also, without the presence of any default arguments, the exact number of arguments passed to a function (call) must be exactly the number declared
  • 22. Positional Arguments- Example >>> def foo(who): # defined for only 1 argument … print 'Hello', who … >>> foo() # 0 arguments… BAD Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: not enough arguments; expected 1, got 0 >>> foo('World!') # 1 argument… WORKS Hello World! >>> foo('Mr.', 'World!')# 2 arguments… BAD Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: too many arguments; expected 1, got 2
  • 23. Variable-length Arguments There may be situations where a function is required to process an unknown number of arguments. These are called variable-length argument lists. Variable-length arguments are not named explicitly in function declarations because the number of arguments is unknown before run-time (and even during execution, the number of arguments may be different on successive calls), an obvious difference from formal arguments (positional and default) which are named in function declarations. Python supports variable-length arguments in two ways because function calls provide for both keyword and non-keyword argument types.
  • 24. Non-keyword Variable Arguments (Tuple) When a function is invoked, all formal (required and default) arguments are assigned to their corresponding local variables as given in the function declaration. The remaining non-keyword variable arguments are inserted in order into a tuple for access. def function_name([formal_args,]*vargs_tuple): "function_documentation_string" function_body_suite
  • 25. Non-keyword Variable Arguments (Tuple) def tupleVarArgs(arg1, arg2='defaultB', *theRest): ‘ display regular args and non-keyword variable args' print 'formal arg 1:', arg1 print 'formal arg 2:', arg1 for eachXtrArg in theRest: print 'another arg:', eachXtrArg
  • 26. Non-keyword Variable Arguments (Tuple) >>> tupleVarArgs('abc') formal arg 1: abc formal arg 2: defaultB >>> tupleVarArgs(23, 4.56) formal arg 1: 23 formal arg 2: 4.56 >>> tupleVarArgs('abc', 123, 'xyz', 456.789) formal arg 1: abc formal arg 2: 123 another arg: xyz another arg: 456.789
  • 27. Keyword Variable Arguments (Dictionary) In the case where we have a variable number or extra set of keyword arguments, these are placed into a dictionary where the "keyworded" argument variable names are the keys, and the arguments are their corresponding values. def function_name([formal_args,][*vargst,] **vargsd): function_documentation_string function_body_suite To differentiate keyword variable arguments from non-keyword informal arguments, a double asterisk ( ** ) is used. The ** is overloaded so it should not be confused with exponentiation. The keyword variable argument dictionary should be the last parameter of the function definition prepended with the '**'.
  • 28. Keyword Variable Arguments (Dictionary) def dictVarArgs(arg1, arg2='defaultB', **theRest): ‘ display 2 regular args and keyword variable args' print ('formal arg1:', dictVarArgs) print( 'formal arg2:', arg2) for eachXtrArg in theRest.keys(): print 'Xtra arg %s: %s' % (eachXtrArg, str(theRest[eachXtrArg]))
  • 29. Keyword Variable Arguments (Dictionary) >>> dictVarArgs(1220, 740.0, c='grail‘) formal arg1: 1220 formal arg2: 740.0 Xtra arg c: grail >>> dictVarArgs('one', d=10, e='zoo', men=('freud', 'gaudi')) formal arg1: one formal arg2: defaultB Xtra arg men: ('freud', 'gaudi') Xtra arg d: 10 Xtra arg e: zoo
  • 30. Keyword Variable Arguments (Dictionary) >>> dictVarArgs(1220, 740.0, c='grail‘) formal arg1: 1220 formal arg2: 740.0 Xtra arg c: grail >>> dictVarArgs('one', d=10, e='zoo', men=('freud', 'gaudi')) formal arg1: one formal arg2: defaultB Xtra arg men: ('freud', 'gaudi') Xtra arg d: 10 Xtra arg e: zoo