SlideShare a Scribd company logo
1 of 25
Functions in Python
The indentation matters…
First line with less
indentation is considered to be
outside of the function definition.
Defining Functions
No header file or declaration of types of function or
arguments
def get_final_answer(filename):
“““Documentation String”””
line1
line2
return total_counter
Function definition begins with “def.” Function name and its arguments.
The keyword ‘return’ indicates the
value to be sent back to the caller.
Colon.
Python and Types
 Dynamic typing: Python determines the data
types of variable bindings in a program
automatically
 Strong typing: But Python’s not casual about
types, it enforces the types of objects
 For example, you can’t just append an integer
to a string, but must first convert it to a string
x = “the answer is ” # x bound to a string
y = 23 # y bound to an integer.
print x + y # Python will complain!
Calling a Function
 The syntax for a function call is:
>>> def myfun(x, y):
return x * y
>>> myfun(3, 4)
12
 Parameters in Python are Call by Assignment
• Old values for the variables that are parameter
names are hidden, and these variables are
simply made to refer to the new values
• All assignment in Python, including binding
function parameters, uses reference semantics.
Functions without returns
 All functions in Python have a return value,
even if no return line inside the code
 Functions without a return return the special
value None
• None is a special constant in the language
• None is used like NULL, void, or nil in other
languages
• None is also logically equivalent to False
• The interpreter’s REPL doesn’t print None
Function overloading? No.
 There is no function overloading in Python
• Unlike C++, a Python function is specified by
its name alone
The number, order, names, or types of arguments
cannot be used to distinguish between two functions
with the same name
• Two different functions can’t have the same
name, even if they have different arguments
 But: see operator overloading in later slides
(Note: van Rossum playing with function overloading for the future)
Default Values for Arguments
 You can provide default values for a
function’s arguments
 These arguments are optional when the
function is called
>>> def myfun(b, c=3, d=“hello”):
return b + c
>>> myfun(5,3,”hello”)
>>> myfun(5,3)
>>> myfun(5)
All of the above function calls return 8
Keyword Arguments
 Can call a function with some/all of its arguments
out of order as long as you specify their names
>>> def foo(x,y,z): return(2*x,4*y,8*z)
>>> foo(2,3,4)
(4, 12, 32)
>>> foo(z=4, y=2, x=3)
(6, 8, 32)
>>> foo(-2, z=-4, y=-3)
(-4, -12, -32)
 Can be combined with defaults, too
>>> def foo(x=1,y=2,z=3): return(2*x,4*y,8*z)
>>> foo()
(2, 8, 24)
>>> foo(z=100)
(2, 8, 800)
Functions are first-class objects
Functions can be used as any other
datatype, eg:
• Arguments to function
• Return values of functions
• Assigned to variables
• Parts of tuples, lists, etc
>>> def square(x): return x*x
>>> def applier(q, x): return q(x)
>>> applier(square, 7)
49
Lambda Notation
Python’s lambda creates anonymous
functions
>>> applier(lambda z: z * 42, 7)
14
Note: only one expression in the lambda
body; its value is always returned
Python supports functional programming
idioms: map, filter, closures,
continuations, etc.
Lambda Notation
Be careful with the syntax
>>> f = lambda x,y : 2 * x + y
>>> f
<function <lambda> at 0x87d30>
>>> f(3, 4)
10
>>> v = lambda x: x*x(100)
>>> v
<function <lambda> at 0x87df0>
>>> v = (lambda x: x*x)(100)
>>> v
10000
Example: composition
>>> def square(x):
return x*x
>>> def twice(f):
return lambda x: f(f(x))
>>> twice
<function twice at 0x87db0>
>>> quad = twice(square)
>>> quad
<function <lambda> at 0x87d30>
>>> quad(5)
625
Example: closure
>>> def counter(start=0, step=1):
x = [start]
def _inc():
x[0] += step
return x[0]
return _inc
>>> c1 = counter()
>>> c2 = counter(100, -10)
>>> c1()
1
>>> c2()
90
map, filter, reduce
>>> def add1(x): return x+1
>>> def odd(x): return x%2 == 1
>>> def add(x,y): return x + y
>>> map(add1, [1,2,3,4])
[2, 3, 4, 5]
>>> map(+,[1,2,3,4],[100,200,300,400])
map(+,[1,2,3,4],[100,200,300,400])
^
SyntaxError: invalid syntax
>>> map(add,[1,2,3,4],[100,200,300,400])
[101, 202, 303, 404]
>>> reduce(add, [1,2,3,4])
10
>>> filter(odd, [1,2,3,4])
[1, 3]
Python
functional programming
Functions are first-class objects
Functions can be used as any other
datatype, eg:
• Arguments to function
• Return values of functions
• Assigned to variables
• Parts of tuples, lists, etc
>>> def square(x): return x*x
>>> def applier(q, x): return q(x)
>>> applier(square, 7)
49
Lambda Notation
Python’s lambda creates anonymous functions
>>> lambda x: x + 1
<function <lambda> at 0x1004e6ed8>
>>> f = lambda x: x + 1
>>> f
<function <lambda> at 0x1004e6f50>
>>> f(100)
101
Lambda Notation
Be careful with the syntax
>>> f = lambda x,y: 2 * x + y
>>> f
<function <lambda> at 0x87d30>
>>> f(3, 4)
10
>>> v = lambda x: x*x(100)
>>> v
<function <lambda> at 0x87df0>
>>> v = (lambda x: x*x)(100)
>>> v
10000
Lambda Notation Limitations
Note: only one expression in the lambda
body; Its value is always returned
The lambda expression must fit on one
line!
Lambda will probably be deprecated in
future versions of python
Guido is not a lambda fanboy
Functional programming
Python supports functional programming
idioms
Builtins for map, reduce, filter, closures,
continuations, etc.
These are often used with lambda
Example: composition
>>> def square(x):
return x*x
>>> def twice(f):
return lambda x: f(f(x))
>>> twice
<function twice at 0x87db0>
>>> quad = twice(square)
>>> quad
<function <lambda> at 0x87d30>
>>> quad(5)
625
Example: closure
>>> def counter(start=0, step=1):
x = [start]
def _inc():
x[0] += step
return x[0]
return _inc
>>> c1 = counter()
>>> c2 = counter(100, -10)
>>> c1()
1
>>> c2()
90
map
>>> def add1(x): return x+1
>>> map(add1, [1,2,3,4])
[2, 3, 4, 5]
>>> map(lambda x: x+1, [1,2,3,4])
[2, 3, 4, 5]
>>> map(+, [1,2,3,4], [100,200,300,400])
map(+,[1,2,3,4],[100,200,300,400])
^
SyntaxError: invalid syntax
map
+ is an operator, not a function
 We can define a corresponding add function
>>> def add(x, y): return x+y
>>> map(add,[1,2,3,4],[100,200,300,400])
[101, 202, 303, 404]
Or import the operator module
>>> from operator import *
>>> map(add, [1,2,3,4], [100,200,300,400])
[101, 202, 303, 404]
>>> map(sub, [1,2,3,4], [100,200,300,400])
[-99, -198, -297, -396]
filter, reduce
Python has buiting for reduce and filter
>>> reduce(add, [1,2,3,4])
10
>>> filter(odd, [1,2,3,4])
[1, 3]
The map, filter and reduce functions
are also at risk 

More Related Content

Similar to 04_python_functions.ppt You can define functions to provide the required functionality.

functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
 
Introduction to Python Basics
Introduction to Python BasicsIntroduction to Python Basics
Introduction to Python BasicsRaghunath A
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013amanabr
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Kurmendra Singh
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in ScalaKnoldus Inc.
 
Functions & closures
Functions & closuresFunctions & closures
Functions & closuresKnoldus Inc.
 
PYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxPYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxgeorgejustymirobi1
 
User defined functions
User defined functionsUser defined functions
User defined functionsshubham_jangid
 

Similar to 04_python_functions.ppt You can define functions to provide the required functionality. (20)

Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
C# programming
C# programming C# programming
C# programming
 
Introduction to Python Basics
Introduction to Python BasicsIntroduction to Python Basics
Introduction to Python Basics
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013Dsp lab _eec-652__vi_sem_18012013
Dsp lab _eec-652__vi_sem_18012013
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
 
Functions & Closures in Scala
Functions & Closures in ScalaFunctions & Closures in Scala
Functions & Closures in Scala
 
Functions & closures
Functions & closuresFunctions & closures
Functions & closures
 
scripting in Python
scripting in Pythonscripting in Python
scripting in Python
 
1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx1. Ch_1 SL_1_Intro to Matlab.pptx
1. Ch_1 SL_1_Intro to Matlab.pptx
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
PYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxPYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptx
 
User defined functions
User defined functionsUser defined functions
User defined functions
 

More from anaveenkumar4

Python Tutorial | Python Programming Language
Python Tutorial | Python Programming LanguagePython Tutorial | Python Programming Language
Python Tutorial | Python Programming Languageanaveenkumar4
 
Electric circuits are classified in several ways. A direct-current circuit ca...
Electric circuits are classified in several ways. A direct-current circuit ca...Electric circuits are classified in several ways. A direct-current circuit ca...
Electric circuits are classified in several ways. A direct-current circuit ca...anaveenkumar4
 
MATLAB UNIT-III.pptx
MATLAB UNIT-III.pptxMATLAB UNIT-III.pptx
MATLAB UNIT-III.pptxanaveenkumar4
 
13012-41797-1-RV.pdf
13012-41797-1-RV.pdf13012-41797-1-RV.pdf
13012-41797-1-RV.pdfanaveenkumar4
 
1-s2.0-S1878029613000716-main.pdf
1-s2.0-S1878029613000716-main.pdf1-s2.0-S1878029613000716-main.pdf
1-s2.0-S1878029613000716-main.pdfanaveenkumar4
 
2_Off_Grid_Grid_Tied.pptx
2_Off_Grid_Grid_Tied.pptx2_Off_Grid_Grid_Tied.pptx
2_Off_Grid_Grid_Tied.pptxanaveenkumar4
 
TRAINING PROGRAMME ON MATLAB ASSOCIATE EXAM (1).pptx
TRAINING PROGRAMME ON MATLAB  ASSOCIATE EXAM (1).pptxTRAINING PROGRAMME ON MATLAB  ASSOCIATE EXAM (1).pptx
TRAINING PROGRAMME ON MATLAB ASSOCIATE EXAM (1).pptxanaveenkumar4
 
9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdfanaveenkumar4
 

More from anaveenkumar4 (13)

Python Tutorial | Python Programming Language
Python Tutorial | Python Programming LanguagePython Tutorial | Python Programming Language
Python Tutorial | Python Programming Language
 
Electric circuits are classified in several ways. A direct-current circuit ca...
Electric circuits are classified in several ways. A direct-current circuit ca...Electric circuits are classified in several ways. A direct-current circuit ca...
Electric circuits are classified in several ways. A direct-current circuit ca...
 
MATLAB UNIT-III.pptx
MATLAB UNIT-III.pptxMATLAB UNIT-III.pptx
MATLAB UNIT-III.pptx
 
project.pptx
project.pptxproject.pptx
project.pptx
 
pump.ppt
pump.pptpump.ppt
pump.ppt
 
RET UNIT-4.pptx
RET UNIT-4.pptxRET UNIT-4.pptx
RET UNIT-4.pptx
 
13012-41797-1-RV.pdf
13012-41797-1-RV.pdf13012-41797-1-RV.pdf
13012-41797-1-RV.pdf
 
SolarThermal.pdf
SolarThermal.pdfSolarThermal.pdf
SolarThermal.pdf
 
1-s2.0-S1878029613000716-main.pdf
1-s2.0-S1878029613000716-main.pdf1-s2.0-S1878029613000716-main.pdf
1-s2.0-S1878029613000716-main.pdf
 
2_Off_Grid_Grid_Tied.pptx
2_Off_Grid_Grid_Tied.pptx2_Off_Grid_Grid_Tied.pptx
2_Off_Grid_Grid_Tied.pptx
 
TRAINING PROGRAMME ON MATLAB ASSOCIATE EXAM (1).pptx
TRAINING PROGRAMME ON MATLAB  ASSOCIATE EXAM (1).pptxTRAINING PROGRAMME ON MATLAB  ASSOCIATE EXAM (1).pptx
TRAINING PROGRAMME ON MATLAB ASSOCIATE EXAM (1).pptx
 
Batch 6.pptx
Batch 6.pptxBatch 6.pptx
Batch 6.pptx
 
9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf9-_Object_Oriented_Programming_Using_Python.pdf
9-_Object_Oriented_Programming_Using_Python.pdf
 

Recently uploaded

(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 

Recently uploaded (20)

(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 

04_python_functions.ppt You can define functions to provide the required functionality.

  • 2. The indentation matters… First line with less indentation is considered to be outside of the function definition. Defining Functions No header file or declaration of types of function or arguments def get_final_answer(filename): “““Documentation String””” line1 line2 return total_counter Function definition begins with “def.” Function name and its arguments. The keyword ‘return’ indicates the value to be sent back to the caller. Colon.
  • 3. Python and Types  Dynamic typing: Python determines the data types of variable bindings in a program automatically  Strong typing: But Python’s not casual about types, it enforces the types of objects  For example, you can’t just append an integer to a string, but must first convert it to a string x = “the answer is ” # x bound to a string y = 23 # y bound to an integer. print x + y # Python will complain!
  • 4. Calling a Function  The syntax for a function call is: >>> def myfun(x, y): return x * y >>> myfun(3, 4) 12  Parameters in Python are Call by Assignment • Old values for the variables that are parameter names are hidden, and these variables are simply made to refer to the new values • All assignment in Python, including binding function parameters, uses reference semantics.
  • 5. Functions without returns  All functions in Python have a return value, even if no return line inside the code  Functions without a return return the special value None • None is a special constant in the language • None is used like NULL, void, or nil in other languages • None is also logically equivalent to False • The interpreter’s REPL doesn’t print None
  • 6. Function overloading? No.  There is no function overloading in Python • Unlike C++, a Python function is specified by its name alone The number, order, names, or types of arguments cannot be used to distinguish between two functions with the same name • Two different functions can’t have the same name, even if they have different arguments  But: see operator overloading in later slides (Note: van Rossum playing with function overloading for the future)
  • 7. Default Values for Arguments  You can provide default values for a function’s arguments  These arguments are optional when the function is called >>> def myfun(b, c=3, d=“hello”): return b + c >>> myfun(5,3,”hello”) >>> myfun(5,3) >>> myfun(5) All of the above function calls return 8
  • 8. Keyword Arguments  Can call a function with some/all of its arguments out of order as long as you specify their names >>> def foo(x,y,z): return(2*x,4*y,8*z) >>> foo(2,3,4) (4, 12, 32) >>> foo(z=4, y=2, x=3) (6, 8, 32) >>> foo(-2, z=-4, y=-3) (-4, -12, -32)  Can be combined with defaults, too >>> def foo(x=1,y=2,z=3): return(2*x,4*y,8*z) >>> foo() (2, 8, 24) >>> foo(z=100) (2, 8, 800)
  • 9. Functions are first-class objects Functions can be used as any other datatype, eg: • Arguments to function • Return values of functions • Assigned to variables • Parts of tuples, lists, etc >>> def square(x): return x*x >>> def applier(q, x): return q(x) >>> applier(square, 7) 49
  • 10. Lambda Notation Python’s lambda creates anonymous functions >>> applier(lambda z: z * 42, 7) 14 Note: only one expression in the lambda body; its value is always returned Python supports functional programming idioms: map, filter, closures, continuations, etc.
  • 11. Lambda Notation Be careful with the syntax >>> f = lambda x,y : 2 * x + y >>> f <function <lambda> at 0x87d30> >>> f(3, 4) 10 >>> v = lambda x: x*x(100) >>> v <function <lambda> at 0x87df0> >>> v = (lambda x: x*x)(100) >>> v 10000
  • 12. Example: composition >>> def square(x): return x*x >>> def twice(f): return lambda x: f(f(x)) >>> twice <function twice at 0x87db0> >>> quad = twice(square) >>> quad <function <lambda> at 0x87d30> >>> quad(5) 625
  • 13. Example: closure >>> def counter(start=0, step=1): x = [start] def _inc(): x[0] += step return x[0] return _inc >>> c1 = counter() >>> c2 = counter(100, -10) >>> c1() 1 >>> c2() 90
  • 14. map, filter, reduce >>> def add1(x): return x+1 >>> def odd(x): return x%2 == 1 >>> def add(x,y): return x + y >>> map(add1, [1,2,3,4]) [2, 3, 4, 5] >>> map(+,[1,2,3,4],[100,200,300,400]) map(+,[1,2,3,4],[100,200,300,400]) ^ SyntaxError: invalid syntax >>> map(add,[1,2,3,4],[100,200,300,400]) [101, 202, 303, 404] >>> reduce(add, [1,2,3,4]) 10 >>> filter(odd, [1,2,3,4]) [1, 3]
  • 16. Functions are first-class objects Functions can be used as any other datatype, eg: • Arguments to function • Return values of functions • Assigned to variables • Parts of tuples, lists, etc >>> def square(x): return x*x >>> def applier(q, x): return q(x) >>> applier(square, 7) 49
  • 17. Lambda Notation Python’s lambda creates anonymous functions >>> lambda x: x + 1 <function <lambda> at 0x1004e6ed8> >>> f = lambda x: x + 1 >>> f <function <lambda> at 0x1004e6f50> >>> f(100) 101
  • 18. Lambda Notation Be careful with the syntax >>> f = lambda x,y: 2 * x + y >>> f <function <lambda> at 0x87d30> >>> f(3, 4) 10 >>> v = lambda x: x*x(100) >>> v <function <lambda> at 0x87df0> >>> v = (lambda x: x*x)(100) >>> v 10000
  • 19. Lambda Notation Limitations Note: only one expression in the lambda body; Its value is always returned The lambda expression must fit on one line! Lambda will probably be deprecated in future versions of python Guido is not a lambda fanboy
  • 20. Functional programming Python supports functional programming idioms Builtins for map, reduce, filter, closures, continuations, etc. These are often used with lambda
  • 21. Example: composition >>> def square(x): return x*x >>> def twice(f): return lambda x: f(f(x)) >>> twice <function twice at 0x87db0> >>> quad = twice(square) >>> quad <function <lambda> at 0x87d30> >>> quad(5) 625
  • 22. Example: closure >>> def counter(start=0, step=1): x = [start] def _inc(): x[0] += step return x[0] return _inc >>> c1 = counter() >>> c2 = counter(100, -10) >>> c1() 1 >>> c2() 90
  • 23. map >>> def add1(x): return x+1 >>> map(add1, [1,2,3,4]) [2, 3, 4, 5] >>> map(lambda x: x+1, [1,2,3,4]) [2, 3, 4, 5] >>> map(+, [1,2,3,4], [100,200,300,400]) map(+,[1,2,3,4],[100,200,300,400]) ^ SyntaxError: invalid syntax
  • 24. map + is an operator, not a function  We can define a corresponding add function >>> def add(x, y): return x+y >>> map(add,[1,2,3,4],[100,200,300,400]) [101, 202, 303, 404] Or import the operator module >>> from operator import * >>> map(add, [1,2,3,4], [100,200,300,400]) [101, 202, 303, 404] >>> map(sub, [1,2,3,4], [100,200,300,400]) [-99, -198, -297, -396]
  • 25. filter, reduce Python has buiting for reduce and filter >>> reduce(add, [1,2,3,4]) 10 >>> filter(odd, [1,2,3,4]) [1, 3] The map, filter and reduce functions are also at risk 