Lesson 1.5: Functions
One of the basic building blocks of computing in Python is the function.
a function takes zero or more input values (called parameters) and returns a result
it also executes commands that can have an effect (sometimes also called a procedure)
The basic structure of a function in Python is the following:
A function in Python always returns a single value.
it can be
None
(similar to null), this is the defaultor it can return the value of some specified expression
or it can return a comma separated sequence of values combined as a tuple
The Components of A Function (1 of 2)
Note: figure courtesy of Professor Thomas Otani, NPS.
The Components of A Function (2 of 2)
Note: figure courtesy of Professor Thomas Otani, NPS.
Passing Data into a Function: Specifying Arguments
Python has two conventions for specifying arguments to a function:
Positional - based on the ordered position in the argument list (we have seen this before)
Keyword - using 'key = value' specification, which ignores positional order (new material)
Mixing Styles
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-20-60e22f32f115> in <module>
1 # you can't specify more than one value for an argument
----> 2 myfunc(5, b=4, a=3)
TypeError: myfunc() got multiple values for argument 'a'
File "<ipython-input-21-87063e8c3423>", line 2
myfunc(a=2,3,4)
^
SyntaxError: positional argument follows keyword argument
Using keyword specification to define default values for parameters
You can define default values using keyword style specification when writing a function.
Providing default values for arguments (when appropriate) can create a lot of flexibility in how you call your functions
Functions can accept arbitrary positional arguments with *args
Activity - Create a my_sum function that:
Accepts any number of inputs and sums them together
Functions can accept arbitrary keyword arguments with **kwargs
Any additional key-value arguments are parsed and stored in a dictionary called kwargs
.
Argument expansions
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-c15edb3ac2c7> in <module>
----> 1 myfunc(x)
TypeError: myfunc() missing 2 required positional arguments: 'b' and 'c'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-497782732eab> in <module>
----> 1 myfunc(mydict)
TypeError: myfunc() missing 2 required positional arguments: 'b' and 'c'
Activity - Create a function that:
Unpacks a tuple, list, or dictionary of length 4 and prints the results
Control Flow (and implications)
When a function is called, a program control flows into the function.
After the function is executed, the control flows back to the calling side.
Only the value of return stament passes back with control flow.
Function parameters are separate copies of arguments (variables):
Parameters are temporary variables that exist in memory only during the execution of the function
Parameters and other local variables are erased from memory after the execution of the function
Any changes you make to parameters during the execution of the function (even if they have the same name as variable in your program) are lost after the function terminates
A function can return only once.
If there is more than one return statement, the first one that is reached is executed
Bottom line: variables that are assigned within a function are local and live only within the scope of that function. It does not matter if they share a name with another variable.
If you want to pass values back to where the function was called, you should return these values.
What happens when you pass a list into a function
Lambda Functions
Python lambdas are little, "anonymous functions", subject to a more restrictive but more concise syntax than regular Python functions.
The Rules:
It can only contain expressions, no statements (i.e. return, pass, assert, or raise will fail).
It needs to be written in a single line
It does not support type annotations
Needs to be immediately invoked
Now let's use multiple inputs
Exploring how Lambdas are used: map, and filter
Map
Mapping is a slick way to loop without specifying interation bounds that are required in constructs such as for
and while
loops.
Mapping "maps" a function (either built in or user defined) to an array of data (list, dictionaries, sets, and tuples).
map
by default returns a mapping iterator and not a array of data.break
andcontinue
do nothing in themap
construct.
Let's consider a very basic example:
Lets take a look at a more complicated example: counting cases in a list
Filter
Used to filter data in a list, tuple, set, or dictionary based on a user specified criteria.
Return an iterator yielding those items of [removed] for which [removed] is true.
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-89-6170e7c0a6e2> in <module>
1 # Let's look at a simple example that doesn't work
2 a=[0,1,2,3,4,5]
----> 3 [a<2]
TypeError: '<' not supported between instances of 'list' and 'int'
Summary
Python has lots of flexibility for specifying function input
The
return
statement is the primary way of sending data out of a functionHowever, if given a references to another object, a function can make changes that are not local
map
,filter
, andlambda
are very useful operations in functional programming.