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