0% found this document useful (0 votes)
3 views36 pages

Pertemuan 3 - Python Function 2

This document provides an overview of Python functions, including their definition, syntax, and how to create user-defined functions. It covers various types of function arguments, such as required, keyword, default, and variable-length arguments, as well as the concept of anonymous functions using lambda. Additionally, it explains higher-order functions like map, filter, and reduce, along with practical examples and use cases.

Uploaded by

dfordebus
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)
3 views36 pages

Pertemuan 3 - Python Function 2

This document provides an overview of Python functions, including their definition, syntax, and how to create user-defined functions. It covers various types of function arguments, such as required, keyword, default, and variable-length arguments, as well as the concept of anonymous functions using lambda. Additionally, it explains higher-order functions like map, filter, and reduce, along with practical examples and use cases.

Uploaded by

dfordebus
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/ 36

Week 4: Python Functions

Function Definition
• A function is a block of organized, reusable code that is used to
perform a single, related action.
• Functions provides better modularity for your application and a high
degree of code reusing.
• As you already know, Python gives you many built-in functions like
print() etc. but you can also create your own functions. These
functions are called user-defined functions.
Define a Function
Here are simple rules to define a function in Python:
• Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
• Characteristics:
• Has a name
• Has parameters (0 or more)
• Has a docstring (optional but recommended)
• Has a body
• Returns something
Python Syntax
• Syntax:
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior, and you need to inform them in the same order
that they were defined.
• Example:
def printme( str ):
"This prints a passed string function"
print (str)
return
Calling a Function
• Following is the example to call printme() function:
def printme( str ): "This is a print function“
print(str)
return

printme("I'm first call to user defined function!")


printme("Again second call to the same function")

• This would produce following result:


I'm first call to user defined function!
Again second call to the same function
Pass by reference vs value
All parameters (arguments) in the Python language are passed by reference. It means
if you change what a parameter refers to within a function, the change also reflects
back in the calling function. For example:
def changeme( mylist ): #This changes a passed list#
mylist.append([1,2,3,4]);
print("Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)

• So this would produce following result:


Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
There is one more example where argument is being passed by reference but inside the
function, but the reference is being over-written.
def changeme( mylist ): #This changes a passed list#
mylist = [1,2,3,4];
print ( "Values inside the function: ", mylist)
return
mylist = [10,20,30];
changeme( mylist );
print ("Values outside the function: ", mylist)

• The parameter mylist is local to the function changeme. Changing mylist within the
function does not affect mylist. The function accomplishes nothing and finally this would
produce following result:
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments:
A function by using the following types of formal arguments::
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments:
• Required arguments are the arguments passed to a function in correct positional
order.
def printme( str ): "This prints a passed string"
print str;
return;
printme();
• This would produce following result:
Traceback (most recent call last):
File "test.py", line 11, in <module> printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments:
• Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
• This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters.
def printme( str ): "This prints a passed string"
print str;
return;
printme( str = "My string");
• This would produce following result:
My string
Following example gives more clear picture. Note, here order of the
parameter does not matter:
def printinfo( name, age ): "Test function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
• This would produce following result:
Name: miki Age 50
Default arguments:
• A default argument is an argument that assumes a default value if a value
is not provided in the function call for that argument.
• Following example gives idea on default arguments, it would print default
age if it is not passed:
def printinfo( name, age = 35 ): #Test function#
print("Name: ", name )
print ("Age ", age )
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
• This would produce following result:
Name: miki Age 50 Name: miki Age 35
Variable-length arguments:
• You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-length
arguments and are not named in the function definition, unlike required
and default arguments.
• The general syntax for a function with non-keyword variable arguments is
this:
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
• An asterisk (*) is placed before the variable name that will hold the values
of all nonkeyword variable arguments. This tuple remains empty if no
additional arguments are specified during the function call. For example:
def printinfo( arg1, *vartuple ):
"This is test"
print ("Output is: ”)
print (arg1)
for var in vartuple:
print (var)
return;
printinfo( 10 );
printinfo( 70, 60, 50 );
• This would produce following result:
Output is:
10
Output is:
70
60
50
The Anonymous Functions:
You can use the lambda keyword to create small anonymous functions. These
functions are called anonymous because they are not declared in the standard
manner by using the def keyword.
• Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an
expression.
• Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
• Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function
stack allocation during invocation for performance reasons.

• Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example:
• Following is the example to show how lambda form of function works:
sum = lambda arg1, arg2: arg1 + arg2;
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ) )
• This would produce following result:
Value of total : 30
Value of total : 40
Scope of Variables:
• All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.
• The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python:
Global variables
Local variables
• Global vs. Local variables:
• Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
• This means that local variables can be accessed only inside the function in which
they are declared whereas global variables can be accessed throughout the
program body by all functions. When you call a function, the variables declared
inside it are brought into scope.
• Example:
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
• This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
Higher Order Functions

Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides.
Except where otherwise noted, this work is licensed under:
http://creativecommons.org/licenses/by-nc-sa/3.0
Functions as parameters
• Have you ever wanted to pass an entire function as a
parameter
• Python has functions as first-class citizens, so you can do
this
• You simply pass the functions by name
Higher-Order Functions
• A higher-order function is a function that takes another
function as a parameter
• They are “higher-order” because it’s a function of a function
• Examples
– Map
– Reduce
– Filter
• Lambda works great as a parameter to higher-order
functions if you can deal with its limitations
Map
map(function, iterable, ...)

• Map applies function to each element of iterable


and creates a list of the results
• You can optionally provide more iterables as
parameters to map and it will place tuples in the
result list
• Map returns an iterator which can be cast to list
Map Example

Example

1 nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3]
2
3 nums = list(map(lambda x : x % 5, nums))
4
5 print(nums)
6 #[0, 4, 2, 2, 1, 0, 4, 3, 0, 1, 3, 0, 3]
7
Map Problem
Goal: given a list of three dimensional points in the
form of tuples, create a new list consisting of the
distances of each point from the origin

Loop Method:
- distance(x, y, z) = sqrt(x**2 + y**2 + z**2)
- loop through the list and add results to a new list
Map Problem

Solution

1 from math import sqrt


2
3 points = [(2, 1, 3), (5, 7, -3), (2, 4, 0), (9, 6, 8)]
4
5 def distance(point) :
6 x, y, z = point
7 return sqrt(x**2 + y**2 + z**2)
8
9 distances = list(map(distance, points))
Filter
filter(function, iterable)
• The filter runs through each element of iterable (any
iterable object such as a List or another collection)
• It applies function to each element of iterable
• If function returns True for that element then the
element is put into a List
• This list is returned from filter in versions of python under
3
• In python 3, filter returns an iterator which must be cast
to type list with list()
Filter Example

Example

1 nums = [0, 4, 7, 2, 1, 0 , 9 , 3, 5, 6, 8, 0, 3]
2
3 nums = list(filter(lambda x : x != 0, nums))
4
5 print(nums) #[4, 7, 2, 1, 9, 3, 5, 6, 8, 3]
6
Filter Problem
NaN = float("nan")
scores = [[NaN, 12, .5, 78, math.pi],
[2, 13, .5, .7, math.pi / 2],
[2, NaN, .5, 78, math.pi],
[2, 14, .5, 39, 1 - math.pi]]

Goal: given a list of lists containing answers to an


algebra exam, filter out those that did not submit a
response for one of the questions, denoted by NaN
Filter Problem
Solution

1 NaN = float("nan")
2 scores = [[NaN, 12, .5, 78, pi],[2, 13, .5, .7, pi / 2],
3 [2,NaN, .5, 78, pi],[2, 14, .5, 39, 1 - pi]]
4 #solution 1 - intuitive
5 def has_NaN(answers) :
6 for num in answers :
7 if isnan(float(num)) :
8 return False
9 return True
0 valid = list(filter(has_NaN, scores))
1 print(valid2)
2 #Solution 2 – sick python solution
3 valid = list(filter(lambda x : NaN not in x, scores))
4 print(valid)
Reduce
reduce(function, iterable[,initializer])

• Reduce will apply function to each element in iterable


along with the sum so far and create a cumulative sum of the
results
• function must take two parameters
• If initializer is provided, initializer will stand as the first
argument in the sum
• Unfortunately in python 3 reduce() requires an import
statement
• from functools import reduce
Reduce Example

Example

1 nums = [1, 2, 3, 4, 5, 6, 7, 8]
2
3 nums = list(reduce(lambda x, y : (x, y), nums))
4
5 Print(nums) #(((((((1, 2), 3), 4), 5), 6), 7), 8)
6
7
Reduce Problem
Goal: given a list of numbers I want to find the
average of those numbers in a few lines using
reduce()

For Loop Method:


- sum up every element of the list
- divide the sum by the length of the list
Reduce Problem

Solution

1 nums = [92, 27, 63, 43, 88, 8, 38, 91, 47, 74, 18, 16,
29, 21, 60, 27, 62, 59, 86, 56]
2
3 sum = reduce(lambda x, y : x + y, nums) / len(nums)
4
MapReduce
A framework for processing huge datasets on certain
kinds of distributable problems

Map Step:
- master node takes the input, chops it up into
smaller sub-problems, and distributes those
to worker nodes.
- worker node may chop its work into yet small
pieces and redistribute again
MapReduce
Reduce Step:
- master node then takes the answers to all the
sub-problems and combines them in a way to get
the output
MapReduce

Problem: Given an email how do you tell if it is spam?

- Count occurrences of certain words. If they


occur too frequently the email is spam.
MapReduce
map_reduce.py

1 email = ['the', 'this', 'annoy', 'the', 'the', 'annoy']


2
3 def inEmail (x):
if (x == "the"):
4 return 1;
5 else:
return 0;
6
map(inEmail, l) #[1, 0, 0, 0, 1, 1, 0]
7
8 reduce((lambda x, xs: x + xs), map(inEmail, email)) #3
9
1
0

You might also like