web/html/ch5func.html~
changeset 1 672eaaab9204
parent 0 8083d21c0020
child 2 52d12eb31c30
equal deleted inserted replaced
0:8083d21c0020 1:672eaaab9204
     1 <html>
       
     2 <head>
       
     3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
       
     4 <title>Chapter 5. Functions </title>
       
     5 <link rel="stylesheet" href="/support/styles.css" type="text/css">
       
     6 <meta name="generator" content="DocBook XSL Stylesheets V1.74.3">
       
     7 <link rel="shortcut icon" type="image/png" href="/support/figs/favicon.png">
       
     8 <script type="text/javascript" src="/support/jquery-min.js"></script>
       
     9 <script type="text/javascript" src="/support/form.js"></script>
       
    10 <script type="text/javascript" src="/support/hsbook.js"></script>
       
    11 <meta name="generator" content="DocBook XSL Stylesheets V1.75.1">
       
    12 </head>
       
    13 <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="chapter" id="ch5func">
       
    14 <div class="titlepage"></div>
       
    15 <div class="toc">
       
    16 <p><b>Table of Contents</b></p>
       
    17 <dl>
       
    18 <dt><span class="article"><a href="#id2436407">Functional Approach</a></span></dt>
       
    19 <dd><dl>
       
    20 <dt><span class="section"><a href="#id2487445">1. Function scope</a></span></dt>
       
    21 <dt><span class="section"><a href="#id2487503">2. Default Arguments</a></span></dt>
       
    22 <dt><span class="section"><a href="#id2487542">3. Keyword Arguments</a></span></dt>
       
    23 <dt><span class="section"><a href="#id2487658">4. Parameter Packing and Unpacking</a></span></dt>
       
    24 <dt><span class="section"><a href="#id2487758">5. Nested Functions and Scopes</a></span></dt>
       
    25 <dt><span class="section"><a href="#id2487811">6. map, reduce and filter functions</a></span></dt>
       
    26 <dd><dl><dt><span class="section"><a href="#id2488001">6.1. List Comprehensions</a></span></dt></dl></dd>
       
    27 </dl></dd>
       
    28 </dl>
       
    29 </div>
       
    30 <div class="article" title="Functional Approach">
       
    31 <div class="titlepage">
       
    32 <div><div><h2 class="title">
       
    33 <a name="id2436407"></a>Functional Approach</h2></div></div>
       
    34 <hr>
       
    35 </div>
       
    36 <div class="toc">
       
    37 <p><b>Table of Contents</b></p>
       
    38 <dl>
       
    39 <dt><span class="section"><a href="#id2487445">1. Function scope</a></span></dt>
       
    40 <dt><span class="section"><a href="#id2487503">2. Default Arguments</a></span></dt>
       
    41 <dt><span class="section"><a href="#id2487542">3. Keyword Arguments</a></span></dt>
       
    42 <dt><span class="section"><a href="#id2487658">4. Parameter Packing and Unpacking</a></span></dt>
       
    43 <dt><span class="section"><a href="#id2487758">5. Nested Functions and Scopes</a></span></dt>
       
    44 <dt><span class="section"><a href="#id2487811">6. map, reduce and filter functions</a></span></dt>
       
    45 <dd><dl><dt><span class="section"><a href="#id2488001">6.1. List Comprehensions</a></span></dt></dl></dd>
       
    46 </dl>
       
    47 </div>
       
    48 <p id="ch5func_1"></a><span class="emphasis"><em>Functions</em></span> allow us to enclose a set of statements and call the function again
       
    49 and again instead of repeating the group of statements everytime. Functions also
       
    50 allow us to isolate a piece of code from all the other code and provides the
       
    51 convenience of not polluting the global variables.</p>
       
    52 <p id="ch5func_2"></a><span class="emphasis"><em>Function</em></span> in python is defined with the keyword <span class="strong"><strong>def</strong></span> followed by the name
       
    53 of the function, in turn followed by a pair of parenthesis which encloses the
       
    54 list of parameters to the function. The definition line ends with a ':'. The
       
    55 definition line is followed by the body of the function intended by one block.
       
    56 The <span class="emphasis"><em>Function</em></span> must return a value:</p>
       
    57 <pre class="programlisting"> def factorial(n):
       
    58   fact = 1
       
    59   for i in range(2, n):
       
    60     fact *= i
       
    61 
       
    62   return fact</pre>
       
    63 <p id="ch5func_3"></a>The code snippet above defines a function with the name factorial, takes the
       
    64 number for which the factorial must be computed, computes the factorial and
       
    65 returns the value.</p>
       
    66 <p id="ch5func_4"></a>A <span class="emphasis"><em>Function</em></span> once defined can be used or called anywhere else in the program. We
       
    67 call a fucntion with its name followed by a pair of parenthesis which encloses
       
    68 the arguments to the function.</p>
       
    69 <p id="ch5func_5"></a>The value that function returns can be assigned to a variable. Let's call the
       
    70 above function and store the factorial in a variable:</p>
       
    71 <pre class="programlisting"> fact5 = factorial(5)</pre>
       
    72 <p id="ch5func_6"></a>The value of fact5 will now be 120, which is the factorial of 5. Note that we
       
    73 passed 5 as the argument to the function.</p>
       
    74 <p id="ch5func_7"></a>It may be necessary to document what the function does, for each of the function
       
    75 to help the person who reads our code to understand it better. In order to do
       
    76 this Python allows the first line of the function body to be a string. This
       
    77 string is called as <span class="emphasis"><em>Documentation String</em></span> or <span class="emphasis"><em>docstring</em></span>. <span class="emphasis"><em>docstrings</em></span> prove
       
    78 to be very handy since there are number of tools which can pull out all the
       
    79 docstrings from Python functions and generate the documentation automatically
       
    80 from it. <span class="emphasis"><em>docstrings</em></span> for functions can be written as follows:</p>
       
    81 <pre class="programlisting"> def factorial(n):
       
    82   'Returns the factorial for the number n.'
       
    83   fact = 1
       
    84   for i in range(2, n):
       
    85     fact *= i
       
    86 
       
    87   return fact</pre>
       
    88 <p id="ch5func_8"></a>An important point to note at this point is that, a function can return any
       
    89 Python value or a Python object, which also includes a <span class="emphasis"><em>Tuple</em></span>. A <span class="emphasis"><em>Tuple</em></span> is
       
    90 just a collection of values and those values themselves can be of any other
       
    91 valid Python datatypes, including <span class="emphasis"><em>Lists</em></span>, <span class="emphasis"><em>Tuples</em></span>, <span class="emphasis"><em>Dictionaries</em></span> among other
       
    92 things. So effectively, if a function can return a tuple, it can return any
       
    93 number of values through a tuple</p>
       
    94 <p id="ch5func_9"></a>Let us write a small function to swap two values:</p>
       
    95 <pre class="programlisting"> def swap(a, b):
       
    96   return b, a
       
    97 
       
    98 c, d = swap(a, b)</pre>
       
    99 <div class="section" title="1. Function scope">
       
   100 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   101 <a name="id2487445"></a>1. Function scope</h2></div></div></div>
       
   102 <p id="ch5func_a"></a>The variables used inside the function are confined to the function's scope
       
   103 and doesn't pollute the variables of the same name outside the scope of the
       
   104 function. Also the arguments passed to the function are passed by-value if
       
   105 it is of basic Python data type:</p>
       
   106 <pre class="programlisting"> def cant_change(n):
       
   107   n = 10
       
   108 
       
   109 n = 5
       
   110 cant_change(n)</pre>
       
   111 <p id="ch5func_b"></a>Upon running this code, what do you think would have happened to value of n
       
   112 which was assigned 5 before the function call? If you have already tried out
       
   113 that snippet on the interpreter you already know that the value of n is not
       
   114 changed. This is true of any immutable types of Python like <span class="emphasis"><em>Numbers</em></span>, <span class="emphasis"><em>Strings</em></span>
       
   115 and <span class="emphasis"><em>Tuples</em></span>. But when you pass mutable objects like <span class="emphasis"><em>Lists</em></span> and <span class="emphasis"><em>Dictionaries</em></span>
       
   116 the values are manipulated even outside the function:</p>
       
   117 <pre class="programlisting"> &gt;&gt;&gt; def can_change(n):
       
   118 ...   n[1] = James
       
   119 ...
       
   120 
       
   121 &gt;&gt;&gt; name = ['Mr.', 'Steve', 'Gosling']
       
   122 &gt;&gt;&gt; can_change(name)
       
   123 &gt;&gt;&gt; name
       
   124 ['Mr.', 'James', 'Gosling']</pre>
       
   125 <p id="ch5func_c"></a>If nothing is returned by the function explicitly, Python takes care to return
       
   126 None when the funnction is called.</p>
       
   127 </div>
       
   128 <div class="section" title="2. Default Arguments">
       
   129 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   130 <a name="id2487503"></a>2. Default Arguments</h2></div></div></div>
       
   131 <p id="ch5func_d"></a>There may be situations where we need to allow the functions to take the
       
   132 arguments optionally. Python allows us to define function this way by providing
       
   133 a facility called <span class="emphasis"><em>Default Arguments</em></span>. For example, we need to write a function
       
   134 that returns a list of fibonacci numbers. Since our function cannot generate an
       
   135 infinite list of fibonacci numbers, we need to specify the number of elements
       
   136 that the fibonacci sequence must contain. Suppose, additionally, we want to the
       
   137 function to return 10 numbers in the sequence if no option is specified we can
       
   138 define the function as follows:</p>
       
   139 <pre class="programlisting"> def fib(n=10):
       
   140   fib_list = [0, 1]
       
   141   for i in range(n - 2):
       
   142     next = fib_list[-2] + fib_list[-1]
       
   143     fib_list.append(next)
       
   144   return fib_list</pre>
       
   145 <p id="ch5func_e"></a>When we call this function, we can optionally specify the value for the
       
   146 parameter n, during the call as an argument. Calling with no argument and
       
   147 argument with n=5 returns the following fibonacci sequences:</p>
       
   148 <pre class="programlisting"> fib()
       
   149 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
       
   150 fib(5)
       
   151 [0, 1, 1, 2, 3]</pre>
       
   152 </div>
       
   153 <div class="section" title="3. Keyword Arguments">
       
   154 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   155 <a name="id2487542"></a>3. Keyword Arguments</h2></div></div></div>
       
   156 <p id="ch5func_f"></a>When a function takes a large number of arguments, it may be difficult to
       
   157 remember the order of the parameters in the function definition or it may
       
   158 be necessary to pass values to only certain parameters since others take
       
   159 the default value. In either of these cases, Python provides the facility
       
   160 of passing arguments by specifying the name of the parameter as defined in
       
   161 the function definition. This is known as <span class="emphasis"><em>Keyword Arguments</em></span>.</p>
       
   162 <p id="ch5func_10"></a>In a function call, <span class="emphasis"><em>Keyword arguments</em></span> can be used for each argument, in the
       
   163 following fashion:</p>
       
   164 <pre class="programlisting"> argument_name=argument_value
       
   165 Also denoted as: keyword=argument
       
   166 
       
   167 def wish(name='World', greetings='Hello'):
       
   168   print "%s, %s!" % (greetings, name)</pre>
       
   169 <p id="ch5func_11"></a>This function can be called in one of the following ways. It is important to
       
   170 note that no restriction is imposed in the order in which <span class="emphasis"><em>Keyword arguments</em></span>
       
   171 can be specified. Also note, that we have combined <span class="emphasis"><em>Keyword arguments</em></span> with
       
   172 <span class="emphasis"><em>Default arguments</em></span> in this example, however it is not necessary:</p>
       
   173 <pre class="programlisting"> wish(name='Guido', greetings='Hey')
       
   174 wish(greetings='Hey', name='Guido')</pre>
       
   175 <p id="ch5func_12"></a>Calling functions by specifying arguments in the order of parameters specified
       
   176 in the function definition is called as <span class="emphasis"><em>Positional arguments</em></span>, as opposed to
       
   177 <span class="emphasis"><em>Keyword arguments</em></span>. It is possible to use both <span class="emphasis"><em>Positional arguments</em></span> and
       
   178 <span class="emphasis"><em>Keyword arguments</em></span> in a single function call. But Python doesn't allow us to
       
   179 bungle up both of them. The arguments to the function, in the call, must always
       
   180 start with <span class="emphasis"><em>Positional arguments</em></span> which is in turn followed by <span class="emphasis"><em>Keyword
       
   181 arguments</em></span>:</p>
       
   182 <pre class="programlisting"> def my_func(x, y, z, u, v, w):
       
   183   # initialize variables.
       
   184   ...
       
   185   # do some stuff
       
   186   ...
       
   187   # return the value</pre>
       
   188 <p id="ch5func_13"></a>It is valid to call the above functions in the following ways:</p>
       
   189 <pre class="programlisting"> my_func(10, 20, 30, u=1.0, v=2.0, w=3.0)
       
   190 my_func(10, 20, 30, 1.0, 2.0, w=3.0)
       
   191 my_func(10, 20, z=30, u=1.0, v=2.0, w=3.0)
       
   192 my_func(x=10, y=20, z=30, u=1.0, v=2.0, w=3.0)</pre>
       
   193 <p id="ch5func_14"></a>Following lists some of the invalid calls:</p>
       
   194 <pre class="programlisting"> my_func(10, 20, z=30, 1.0, 2.0, 3.0)
       
   195 my_func(x=10, 20, z=30, 1.0, 2.0, 3.0)
       
   196 my_func(x=10, y=20, z=30, u=1.0, v=2.0, 3.0)</pre>
       
   197 </div>
       
   198 <div class="section" title="4. Parameter Packing and Unpacking">
       
   199 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   200 <a name="id2487658"></a>4. Parameter Packing and Unpacking</h2></div></div></div>
       
   201 <p id="ch5func_15"></a>The positional arguments passed to a function can be collected in a tuple
       
   202 parameter and keyword arguments can be collected in a dictionary. Since keyword
       
   203 arguments must always be the last set of arguments passed to a function, the
       
   204 keyword dictionary parameter must be the last parameter. The function definition
       
   205 must include a list explicit parameters, followed by tuple paramter collecting
       
   206 parameter, whose name is preceded by a <span class="strong"><strong>*</strong></span>, for collecting positional
       
   207 parameters, in turn followed by the dictionary collecting parameter, whose name
       
   208 is preceded by a <span class="strong"><strong>**</strong></span></p>
       
   209 <pre class="programlisting"> def print_report(title, *args, **name):
       
   210   """Structure of *args*
       
   211   (age, email-id)
       
   212   Structure of *name*
       
   213   {
       
   214       'first': First Name
       
   215       'middle': Middle Name
       
   216       'last': Last Name
       
   217   }
       
   218   """
       
   219 
       
   220   print "Title: %s" % (title)
       
   221   print "Full name: %(first)s %(middle)s %(last)s" % name
       
   222   print "Age: %d\nEmail-ID: %s" % args</pre>
       
   223 <p id="ch5func_16"></a>The above function can be called as. Note, the order of keyword parameters can
       
   224 be interchanged:</p>
       
   225 <pre class="programlisting"> &gt;&gt;&gt; print_report('Employee Report', 29, 'johny@example.com', first='Johny',
       
   226                  last='Charles', middle='Douglas')
       
   227 Title: Employee Report
       
   228 Full name: Johny Douglas Charles
       
   229 Age: 29
       
   230 Email-ID: johny@example.com</pre>
       
   231 <p id="ch5func_17"></a>The reverse of this can also be achieved by using a very identical syntax while
       
   232 calling the function. A tuple or a dictionary can be passed as arguments in
       
   233 place of a list of <span class="emphasis"><em>Positional arguments</em></span> or <span class="emphasis"><em>Keyword arguments</em></span> respectively
       
   234 using <span class="strong"><strong>*</strong></span> or <span class="strong"><strong>**</strong></span></p>
       
   235 <pre class="programlisting"> def print_report(title, age, email, first, middle, last):
       
   236   print "Title: %s" % (title)
       
   237   print "Full name: %s %s %s" % (first, middle, last)
       
   238   print "Age: %d\nEmail-ID: %s" % (age, email)
       
   239 
       
   240 &gt;&gt;&gt; args = (29, 'johny@example.com')
       
   241 &gt;&gt;&gt; name = {
       
   242         'first': 'Johny',
       
   243         'middle': 'Charles',
       
   244         'last': 'Douglas'
       
   245         }
       
   246 &gt;&gt;&gt; print_report('Employee Report', *args, **name)
       
   247 Title: Employee Report
       
   248 Full name: Johny Charles Douglas
       
   249 Age: 29
       
   250 Email-ID: johny@example.com</pre>
       
   251 </div>
       
   252 <div class="section" title="5. Nested Functions and Scopes">
       
   253 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   254 <a name="id2487758"></a>5. Nested Functions and Scopes</h2></div></div></div>
       
   255 <p id="ch5func_18"></a>Python allows nesting one function inside another. This style of programming
       
   256 turns out to be extremely flexible and powerful features when we use <span class="emphasis"><em>Python
       
   257 decorators</em></span>. We will not talk about decorators is beyond the scope of this
       
   258 course. If you are interested in knowing more about <span class="emphasis"><em>decorator programming</em></span> in
       
   259 Python you are suggested to read:</p>
       
   260 <span style="color: black">&lt;line_block&gt;<span style="color: black">&lt;line&gt;<div class="reference">
       
   261 <div class="titlepage"><hr></div>http://avinashv.net/2008/04/python-decorators-syntactic-sugar/</div>&lt;/line&gt;</span><span style="color: black">&lt;line&gt;<div class="reference">
       
   262 <div class="titlepage"><hr></div>http://personalpages.tds.net/~kent37/kk/00001.html</div>&lt;/line&gt;</span>&lt;/line_block&gt;</span><p id="ch5func_19"></a>However, the following is an example for nested functions in Python:</p>
       
   263 <pre class="programlisting"> def outer():
       
   264   print "Outer..."
       
   265   def inner():
       
   266     print "Inner..."
       
   267   print "Outer..."
       
   268   inner()
       
   269 
       
   270 &gt;&gt;&gt; outer()</pre>
       
   271 </div>
       
   272 <div class="section" title="6. map, reduce and filter functions">
       
   273 <div class="titlepage"><div><div><h2 class="title" style="clear: both">
       
   274 <a name="id2487811"></a>6. map, reduce and filter functions</h2></div></div></div>
       
   275 <p id="ch5func_1a"></a>Python provides several built-in functions for convenience. The <span class="strong"><strong>map()</strong></span>,
       
   276 <span class="strong"><strong>reduce()</strong></span> and <span class="strong"><strong>filter()</strong></span> functions prove to be very useful with sequences like
       
   277 <span class="emphasis"><em>Lists</em></span>.</p>
       
   278 <p id="ch5func_1b"></a>The <span class="strong"><strong>map</strong></span> (<span class="emphasis"><em>function</em></span>, <span class="emphasis"><em>sequence</em></span>) function takes two arguments: <span class="emphasis"><em>function</em></span>
       
   279 and a <span class="emphasis"><em>sequence</em></span> argument. The <span class="emphasis"><em>function</em></span> argument must be the name of the
       
   280 function which in turn takes a single argument, the individual element of the
       
   281 <span class="emphasis"><em>sequence</em></span>. The <span class="strong"><strong>map</strong></span> function calls <span class="emphasis"><em>function(item)</em></span>, for each item in the
       
   282 sequence and returns a list of values, where each value is the value returned
       
   283 by each call to <span class="emphasis"><em>function(item)</em></span>. <span class="strong"><strong>map()</strong></span> function allows to pass more than
       
   284 one sequence. In this case, the first argument, <span class="emphasis"><em>function</em></span> must take as many
       
   285 arguments as the number of sequences passed. This function is called with each
       
   286 corresponding element in the each of the sequences, or <span class="strong"><strong>None</strong></span> if one of the
       
   287 sequence is exhausted:</p>
       
   288 <pre class="programlisting"> def square(x):
       
   289   return x*x
       
   290 
       
   291 &gt;&gt;&gt; map(square, [1, 2, 3, 4])
       
   292 [1, 4, 9, 16]
       
   293 
       
   294 def mul(x, y):
       
   295   return x*y
       
   296 
       
   297 &gt;&gt;&gt; map(mul, [1, 2, 3, 4], [6, 7, 8, 9])</pre>
       
   298 <p id="ch5func_1c"></a>The <span class="strong"><strong>filter</strong></span> (<span class="emphasis"><em>function</em></span>, <span class="emphasis"><em>sequence</em></span>) function takes two arguments, similar to
       
   299 the <span class="strong"><strong>map()</strong></span> function. The <span class="strong"><strong>filter</strong></span> function calls <span class="emphasis"><em>function(item)</em></span>, for each
       
   300 item in the sequence and returns all the elements in the sequence for which
       
   301 <span class="emphasis"><em>function(item)</em></span> returned True:</p>
       
   302 <pre class="programlisting"> def even(x):
       
   303   if x % 2:
       
   304     return True
       
   305   else:
       
   306     return False
       
   307 
       
   308 &gt;&gt;&gt; filter(even, range(1, 10))
       
   309 [1, 3, 5, 7, 9]</pre>
       
   310 <p id="ch5func_1d"></a>The <span class="strong"><strong>reduce</strong></span> (<span class="emphasis"><em>function</em></span>, <span class="emphasis"><em>sequence</em></span>) function takes two arguments, similar to
       
   311 <span class="strong"><strong>map</strong></span> function, however multiple sequences are not allowed. The <span class="strong"><strong>reduce</strong></span>
       
   312 function calls <span class="emphasis"><em>function</em></span> with first two consecutive elements in the sequence,
       
   313 obtains the result, calls <span class="emphasis"><em>function</em></span> with the result and the subsequent element
       
   314 in the sequence and so on until the end of the list and returns the final result:</p>
       
   315 <pre class="programlisting"> def mul(x, y):
       
   316   return x*y
       
   317 
       
   318 &gt;&gt;&gt; reduce(mul, [1, 2, 3, 4])
       
   319 24</pre>
       
   320 <div class="section" title="6.1. List Comprehensions">
       
   321 <div class="titlepage"><div><div><h3 class="title">
       
   322 <a name="id2488001"></a>6.1. List Comprehensions</h3></div></div></div>
       
   323 <p id="ch5func_1e"></a>List Comprehension is a convenvience utility provided by Python. It is a
       
   324 syntatic sugar to create <span class="emphasis"><em>Lists</em></span>. Using <span class="emphasis"><em>List Comprehensions</em></span> one can create
       
   325 <span class="emphasis"><em>Lists</em></span> from other type of sequential data structures or other <span class="emphasis"><em>Lists</em></span> itself.
       
   326 The syntax of <span class="emphasis"><em>List Comprehensions</em></span> consists of a square brackets to indicate
       
   327 the result is a <span class="emphasis"><em>List</em></span> within which we include at least one <span class="strong"><strong>for</strong></span> clause and
       
   328 multiple <span class="strong"><strong>if</strong></span> clauses. It will be more clear with an example:</p>
       
   329 <pre class="programlisting"> &gt;&gt;&gt; num = [1, 2, 3]
       
   330 &gt;&gt;&gt; sq = [x*x for x in num]
       
   331 &gt;&gt;&gt; sq
       
   332 [1, 4, 9]
       
   333 &gt;&gt;&gt; all_num = [1, 2, 3, 4, 5, 6, 7, 8, 9]
       
   334 &gt;&gt;&gt; even = [x for x in all_num if x%2 == 0]</pre>
       
   335 <p id="ch5func_1f"></a>The syntax used here is very clear from the way it is written. It can be
       
   336 translated into english as, "for each element x in the list all_num,
       
   337 if remainder of x divided by 2 is 0, add x to the list."</p>
       
   338 </div>
       
   339 </div>
       
   340 </div>
       
   341 </div></body>
       
   342 </html>