getting_started_with_functions/script.rst
changeset 522 d33698326409
equal deleted inserted replaced
521:88a01948450d 522:d33698326409
       
     1 .. Objectives
       
     2 .. ----------
       
     3 
       
     4 .. 8.1 LO: getting started with functions (3)
       
     5 
       
     6 .. At the end of this tutorial, you will be able to 
       
     7 
       
     8 .. 1. define function
       
     9 .. #. define functions with arguments
       
    10 .. #. learn about docstrings
       
    11 .. #. learn about return values
       
    12 ..     can return multiple values
       
    13 .. #. read code
       
    14 
       
    15 
       
    16 .. Prerequisites
       
    17 .. -------------
       
    18 
       
    19 ..   1. should have ``ipython`` installed. 
       
    20 ..   #. getting started with ``ipython``.
       
    21 
       
    22      
       
    23 .. Author              : Anoop Jacob Thomas <anoop@fossee.in>
       
    24    Internal Reviewer   : 
       
    25    External Reviewer   :
       
    26    Language Reviewer   : Bhanukiran
       
    27    Checklist OK?       : <put date stamp here, not OK> [2010-10-05]
       
    28 
       
    29 
       
    30 ==============================
       
    31 Getting started with functions
       
    32 ==============================
       
    33 
       
    34 {{{ show welcome slide }}}
       
    35 
       
    36 Hello and welcome to the tutorial getting started with functions.
       
    37 
       
    38 {{{ switch to next slide, outline slide }}}
       
    39 
       
    40 In this tutorial we will learn about functions in python, how to
       
    41 define functions, arguments to functions, docstrings, and function
       
    42 return value.
       
    43 
       
    44 {{{ switch to next slide, Function }}}
       
    45 
       
    46 While writing code, we always want to reduce the number of lines of
       
    47 code and functions is a way of reusing the code. Thus the same lines
       
    48 of code can be used as many times as needed. A function is a portion of code
       
    49 within a larger program that performs a specific task and is
       
    50 relatively independent of the remaining code. Now let us get more
       
    51 familiar with functions,
       
    52 
       
    53 {{{ switch to next slide, f(x) a mathematical function }}}
       
    54 
       
    55 Consider a mathematical function f(x) = x square. Here x is a variable
       
    56 and with different values of x the value of function will change. When
       
    57 x is one f(1) will return the value 1 and f(2) will return us the
       
    58 value 4. Let us now see how to define the function f(x) in python.
       
    59 
       
    60 {{{ switch to next slide, define f(x) in Python }}}
       
    61 
       
    62 In your Ipython interpreter type the following,
       
    63 ::
       
    64 
       
    65     def f(x):
       
    66     	return x*x
       
    67 
       
    68 Well that defined the function, so before learning what we did let us
       
    69 see if it returns the expected values, try,
       
    70 ::
       
    71 
       
    72     f(1)
       
    73     f(2)
       
    74 
       
    75 Yes, it returned 1 and 4 respectively. And now let us see what we did.
       
    76 We wrote two lines: The first line ``def f(x)`` is used to define the
       
    77 name and the parameters to the function and the second line is used to
       
    78 fix what the function is supposed to return. ``def`` is a keyword and
       
    79 ``f`` is the name of the function and ``x`` the parameter of the
       
    80 function.
       
    81 
       
    82 {{{ switch to next slide, problem statement 1 }}}
       
    83 
       
    84 %% 1 %% Write a python function named cube which computes the cube of
       
    85    a given number n.
       
    86 
       
    87 Pause here and try to solve the problem yourself.
       
    88 
       
    89 {{{ switch to next slide, solution }}}
       
    90 
       
    91 The problem can be solved as,
       
    92 ::
       
    93 
       
    94     def cube(n):
       
    95     	return n**3
       
    96 
       
    97 And now let us see how to write functions without arguments.
       
    98 
       
    99 {{{ switch to next slide, greet function }}}
       
   100 
       
   101 let us define a new function called ``greet`` which will print ``Hello
       
   102 World``.
       
   103 ::
       
   104 
       
   105     def greet():
       
   106     	print "Hello World!"
       
   107 
       
   108 now try calling the function,
       
   109 ::
       
   110 
       
   111     greet()
       
   112 
       
   113 Well that is a function which takes no arguments. Also note that it is
       
   114 not mandatory for a function to return values. The function ``greet``
       
   115 neither takes any argument nor returns any value.
       
   116 
       
   117 Now let us see how to write functions with more than one argument.
       
   118 
       
   119 {{{ switch to next slide, exercise 2 }}}
       
   120 
       
   121 %% 2 %% Write a python function named ``avg`` which computes the
       
   122    average of ``a`` and ``b``.
       
   123 
       
   124 Pause here and try to solve the problem yourself.
       
   125 
       
   126 {{{ switch to next slide, solution 2 }}}
       
   127 
       
   128 The problem can be solved as,
       
   129 ::
       
   130 
       
   131     def avg(a,b):
       
   132     	return (a + b)/2
       
   133 
       
   134 Thus if we want a function to accept more arguments, we just list them
       
   135 separated with a comma between the parenthesis after the function's name
       
   136 in the ``def`` line.
       
   137 
       
   138 {{{ switch to next slide, docstring }}}
       
   139 
       
   140 It is always a good practice to document the code that we write, and
       
   141 for a function we define we should write an abstract of what the
       
   142 function does, and that is called a docstring. Let us modify the
       
   143 function ``avg`` and add docstring to it. Do the following,
       
   144 ::
       
   145 
       
   146     def avg(a,b):
       
   147         """ avg takes two numbers as input (a & b), and
       
   148 	returns the average of a and b"""
       
   149 	return (a+b)/2
       
   150 
       
   151 Note that docstrings are entered in the immediate line after the
       
   152 function definition and put as a triple quoted string. And here as far
       
   153 as the code functionality is concerned, we didn't do anything. We just
       
   154 added an abstract of what the function does.
       
   155 
       
   156 Now try this in the ipython interpreter.
       
   157 ::
       
   158 
       
   159     avg?
       
   160 
       
   161 It displays the docstring as we gave it. Thus docstring is a good way
       
   162 of documenting the function we write.
       
   163 
       
   164 Try to do this,
       
   165 ::
       
   166 
       
   167     f?
       
   168 
       
   169 It doesn't have a docstring associated with it. Also we cannot infer
       
   170 anything from the function name, and thus we are forced to read the
       
   171 code to understand about the function.
       
   172 
       
   173 {{{ switch to next slide, exercise 3 }}}
       
   174 
       
   175 %% 3 %% Add docstring to the function f.
       
   176 
       
   177 Pause here and try to do it yourself.
       
   178 
       
   179 {{{ switch to next slide, solution }}}
       
   180 
       
   181 We need to define the function again to add docstring to the function
       
   182 ``f`` and we do it as,
       
   183 ::
       
   184 
       
   185     def f(x):
       
   186     	"""Accepts a number x as argument and,
       
   187 	returns the square of the number x."""
       
   188 	return x*x
       
   189 
       
   190 {{{ switch to next slide, exercise 4 }}}
       
   191 
       
   192 %% 4 %% Write a python function named ``circle`` which returns the
       
   193    area and perimeter of a circle given radius ``r``.
       
   194 
       
   195 Pause here and try to solve the problem yourself.
       
   196 
       
   197 {{{ switch to next slide, solution 4 }}}
       
   198 
       
   199 The problem requires us to return two values instead of one which we
       
   200 were doing till now. We can solve the problem as,
       
   201 ::
       
   202 
       
   203     def circle(r):
       
   204     	"""returns area and perimeter of a circle given radius r"""
       
   205 	pi = 3.14
       
   206 	area = pi * r * r
       
   207 	perimeter = 2 * pi * r
       
   208 	return area, perimeter
       
   209 
       
   210 A python function can return any number of values. There is no
       
   211 restriction for it.
       
   212 
       
   213 Let us call the function ``circle`` as,
       
   214 ::
       
   215 
       
   216     a, p = circle(6)
       
   217     print a
       
   218     print p
       
   219 
       
   220 Now we have done enough coding, let us do some code reading exercise,
       
   221 
       
   222 {{{ switch to next slide, what }}}
       
   223 
       
   224 What does the function ``what`` do?
       
   225 
       
   226 .. def what( n ):
       
   227 ..     if n < 0: n = -n
       
   228 ..     while n > 0:
       
   229 ..         if n % 2 == 1:
       
   230 ..             return False
       
   231 ..         n /= 10
       
   232 ..     return True
       
   233 
       
   234 Pause here and try to figure out what the function ``what`` does.
       
   235 
       
   236 {{{ switch to next slide, even_digits }}}
       
   237 
       
   238 .. def even_digits( n ):
       
   239 ..    """returns True if all the digits in the number n are even,
       
   240 ..    returns False if all the digits in the number n are not even"""
       
   241 ..     if n < 0: n = -n
       
   242 ..     while n > 0:
       
   243 ..         if n % 2 == 1:
       
   244 ..             return False
       
   245 ..         n /= 10
       
   246 ..     return True
       
   247 
       
   248 The function returns ``True`` if all the digits of the number ``n``
       
   249 are even, otherwise it returns ``False``.
       
   250 
       
   251 Now one more code reading exercise,
       
   252 
       
   253 {{{ switch to next slide, what }}}
       
   254 
       
   255 What does the function ``what`` do?
       
   256 
       
   257 .. def what( n ):
       
   258 ..     i = 1
       
   259 ..     while i * i < n:
       
   260 ..         i += 1
       
   261 ..     return i * i == n, i
       
   262 
       
   263 Pause here and try to figure out what the function ``what`` does.
       
   264 
       
   265 {{{ switch to next slide, is_perfect_square }}}
       
   266 
       
   267 .. def is_perfect_square( n ):
       
   268 ..     """returns True and square root of n, if n is a perfect square,
       
   269 ..     otherwise returns False and the square root of the 
       
   270 ..     next perfect square"""
       
   271 ..     i = 1
       
   272 ..     while i * i < n:
       
   273 ..         i += 1
       
   274 ..     return i * i == n, i
       
   275 
       
   276 
       
   277 The function returns ``True`` and the square root of ``n`` if n is a
       
   278 perfect square, otherwise it returns ``False`` and the square root of
       
   279 the next perfect square.
       
   280 
       
   281 This brings us to the end of this tutorial, in this tutorial we covered
       
   282 
       
   283 {{{ switch to next slide, summary }}}
       
   284 
       
   285 - Functions in Python
       
   286 - Passing parameters to a function
       
   287 - Returning values from a function
       
   288 
       
   289 We also did few code reading exercises.
       
   290 
       
   291 {{{ switch to next slide, Thank you }}}
       
   292 
       
   293 Thank you!