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