0% found this document useful (0 votes)
30 views27 pages

Functions

Python has two types of functions: built-in functions provided by Python and user-defined functions. Functions are defined using the def keyword and take arguments. Functions can return values using the return statement. Functions allow for code reuse and organization.

Uploaded by

Sam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views27 pages

Functions

Python has two types of functions: built-in functions provided by Python and user-defined functions. Functions are defined using the def keyword and take arguments. Functions can return values using the return statement. Functions allow for code reuse and organization.

Uploaded by

Sam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Functions in Python

Python Functions

There are two kinds of functions in Python.

- Built-in functions that are provided as part of Python


- print(), input(), type(), float(), int() ...

- Functions that we define ourselves and then use

• We treat function names as “new” reserved words


(i.e., we avoid them as variable names)
Function Definition

• In Python a function is some reusable code that takes


arguments(s) as input, does some computation, and
then returns a result or results

• We define a function using the def reserved word

• We call/invoke the function by using the function


name, parentheses, and arguments in an expression
Defining Functions
Function definition begins with “def.” Function name and its arguments.

def get_final_answer(filename):
“““Documentation String”””
line1
line2 Colon.
return total_counter

The indentation matters…


First line with less
indentation is considered to be The keyword ‘return’ indicates the
outside of the function definition. value to be sent back to the caller.

No header file or declaration of types of function or


arguments
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
Building our Own Functions

• We create a new function using the def keyword followed by


optional parameters in parentheses

• We indent the body of the function

• This defines the function but does not execute the body of the
function

def print_lyrics():
print("I'm a lumberjack, and I'm
okay.")
print('I sleep all night and I
work all day.')
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

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
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 
Definitions and Uses

• Once we have defined a function, we can call (or


invoke) it as many times as we like

• This is the store and reuse pattern


Arguments

• An argument is a value we pass into the function as its input


when we call the function

• We use arguments so we can direct the function to do different


kinds of work when we call it at different times

• We put the arguments in parentheses after the name of the


function
big = max('Hello world')
Argument
Multiple Parameters /
Arguments

• We can define more than one


parameter in the function def addtwo(a, b):
added = a + b
definition
return added
• We simply add more arguments x = addtwo(3, 5)
when we call the function print(x)

• We match the number and order 8


of arguments and parameters
Void (non-fruitful) Functions

• When a function does not return a value, we call it a “void”


function

• Functions that return values are “fruitful” functions


• Void functions are “not fruitful”
To function or not to
function...

• Organize your code into “paragraphs” - capture a complete


thought and “name it”

• Don’t repeat yourself - make it work once and then reuse it

• If something gets too long or complex, break it up into logical


chunks and put those chunks in functions

• Make a library of common stuff that you do over and over -


perhaps share this with your friends...

You might also like