SlideShare a Scribd company logo
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
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
•
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
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):
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
>>> f = lambda x,y
:
2 *
x
+ y
>>> f
Be careful with the syntax
<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
c2
= counter()
= 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
>>> f = lambda x,y: 2 *
x
+ y
>>> f
Be careful with the syntax
<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
c2
= counter()
= 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])
^
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]
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

PPT
04_python_functions.ppt You can define functions to provide the required func...
PPTX
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
PDF
Functions in python
PPT
python language programming presentation
ODP
Functions In Scala
PDF
cel shading as PDF and Python description
PPTX
matlab presentation fro engninering students
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
04_python_functions.ppt You can define functions to provide the required func...
Function in Python.pptx by Faculty at gla university in mathura uttar pradesh
Functions in python
python language programming presentation
Functions In Scala
cel shading as PDF and Python description
matlab presentation fro engninering students
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd

Similar to Python Introduction 2 Deep Learning.pptx (20)

PPTX
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
PPTX
C++ lecture 03
PDF
Functions_21_22.pdf
PPTX
OOPS Object oriented Programming PPT Tutorial
ODP
Python basics
PDF
Chapter Functions for grade 12 computer Science
PPTX
Functions in Python Programming Language
PPT
cpphtp4_PPT_03.ppt
PPTX
Working with functions.pptx. Hb.
PPTX
Python programming- Part IV(Functions)
PPTX
Generators-in-Python-for-Developers.pptx
PDF
Python Function
PDF
Functionscs12 ppt.pdf
PDF
Functions.pdf
PPT
User defined functions
PDF
Python lambda functions with filter, map & reduce function
PDF
All About ... Functions
PPT
functions modules and exceptions handlings.ppt
PPTX
JNTUK python programming python unit 3.pptx
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
C++ lecture 03
Functions_21_22.pdf
OOPS Object oriented Programming PPT Tutorial
Python basics
Chapter Functions for grade 12 computer Science
Functions in Python Programming Language
cpphtp4_PPT_03.ppt
Working with functions.pptx. Hb.
Python programming- Part IV(Functions)
Generators-in-Python-for-Developers.pptx
Python Function
Functionscs12 ppt.pdf
Functions.pdf
User defined functions
Python lambda functions with filter, map & reduce function
All About ... Functions
functions modules and exceptions handlings.ppt
JNTUK python programming python unit 3.pptx
Ad

Recently uploaded (20)

PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Sports Quiz easy sports quiz sports quiz
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
RMMM.pdf make it easy to upload and study
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Cell Structure & Organelles in detailed.
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
Pre independence Education in Inndia.pdf
PPTX
Lesson notes of climatology university.
PPTX
Cell Types and Its function , kingdom of life
PDF
Basic Mud Logging Guide for educational purpose
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
01-Introduction-to-Information-Management.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Sports Quiz easy sports quiz sports quiz
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Module 4: Burden of Disease Tutorial Slides S2 2025
RMMM.pdf make it easy to upload and study
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Cell Structure & Organelles in detailed.
Insiders guide to clinical Medicine.pdf
Microbial diseases, their pathogenesis and prophylaxis
PPH.pptx obstetrics and gynecology in nursing
Pre independence Education in Inndia.pdf
Lesson notes of climatology university.
Cell Types and Its function , kingdom of life
Basic Mud Logging Guide for educational purpose
O5-L3 Freight Transport Ops (International) V1.pdf
Abdominal Access Techniques with Prof. Dr. R K Mishra
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
01-Introduction-to-Information-Management.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Ad

Python Introduction 2 Deep Learning.pptx

  • 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
  • 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 •
  • 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
  • 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):
  • 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 >>> f = lambda x,y : 2 * x + y >>> f Be careful with the syntax <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 c2 = counter() = 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 >>> f = lambda x,y: 2 * x + y >>> f Be careful with the syntax <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 c2 = counter() = 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]) ^
  • 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]
  • 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 