Pertemuan 3 - Python Function 2
Pertemuan 3 - Python Function 2
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
• 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, ...)
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
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]]
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])
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()
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