functions.asciidoc 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. [[functions]]
  2. == Functions
  3. Functions are reusable pieces of programs. They allow you to give a name to a block of statements,
  4. allowing you to run that block using the specified name anywhere in your program and any number of
  5. times. This is known as *calling* the function. We have already used many built-in functions such
  6. as `len` and `range`.
  7. The function concept is probably *the* most important building block of any non-trivial software
  8. (in any programming language), so we will explore various aspects of functions in this chapter.
  9. Functions are defined using the `def` keyword. After this keyword comes an *identifier* name for
  10. the function, followed by a pair of parentheses which may enclose some names of variables, and by
  11. the final colon that ends the line. Next follows the block of statements that are part of this
  12. function. An example will show that this is actually very simple:
  13. Example (save as `function1.py`):
  14. [source,python]
  15. --------------------------------------------------
  16. include::programs/function1.py[]
  17. --------------------------------------------------
  18. Output:
  19. --------------------------------------------------
  20. include::programs/function1.txt[]
  21. --------------------------------------------------
  22. .How It Works
  23. We define a function called `say_hello` using the syntax as explained above. This function takes no
  24. parameters and hence there are no variables declared in the parentheses. Parameters to functions
  25. are just input to the function so that we can pass in different values to it and get back
  26. corresponding results.
  27. Notice that we can call the same function twice which means we do not have to write the same code
  28. again.
  29. [[function_parameters]]
  30. === Function Parameters
  31. A function can take parameters, which are values you supply to the function so that the function
  32. can *do* something utilising those values. These parameters are just like variables except that the
  33. values of these variables are defined when we call the function and are already assigned values
  34. when the function runs.
  35. Parameters are specified within the pair of parentheses in the function definition, separated by
  36. commas. When we call the function, we supply the values in the same way. Note the terminology
  37. used - the names given in the function definition are called *parameters* whereas the values you
  38. supply in the function call are called *arguments*.
  39. Example (save as `function_param.py`):
  40. [source,python]
  41. --------------------------------------------------
  42. include::programs/function_param.py[]
  43. --------------------------------------------------
  44. Output:
  45. --------------------------------------------------
  46. include::programs/function_param.txt[]
  47. --------------------------------------------------
  48. .How It Works
  49. Here, we define a function called `print_max` that uses two parameters called `a` and `b`. We find
  50. out the greater number using a simple `if..else` statement and then print the bigger number.
  51. The first time we call the function `print_max`, we directly supply the numbers as arguments. In
  52. the second case, we call the function with variables as arguments. `print_max(x, y)` causes the
  53. value of argument `x` to be assigned to parameter `a` and the value of argument `y` to be assigned
  54. to parameter `b`. The `print_max` function works the same way in both cases.
  55. [[local_variables]]
  56. === Local Variables
  57. When you declare variables inside a function definition, they are not related in any way to other
  58. variables with the same names used outside the function - i.e. variable names are *local* to the
  59. function. This is called the *scope* of the variable. All variables have the scope of the block
  60. they are declared in starting from the point of definition of the name.
  61. Example (save as `function_local.py`):
  62. [source,python]
  63. --------------------------------------------------
  64. include::programs/function_local.py[]
  65. --------------------------------------------------
  66. Output:
  67. --------------------------------------------------
  68. include::programs/function_local.txt[]
  69. --------------------------------------------------
  70. .How It Works
  71. The first time that we print the *value* of the name *x* with the first line in the function's
  72. body, Python uses the value of the parameter declared in the main block, above the function
  73. definition.
  74. Next, we assign the value `2` to `x`. The name `x` is local to our function. So, when we change
  75. the value of `x` in the function, the `x` defined in the main block remains unaffected.
  76. With the last `print` statement, we display the value of `x` as defined in the main block, thereby
  77. confirming that it is actually unaffected by the local assignment within the previously called
  78. function.
  79. [[the_global_statement]]
  80. === The +global+ statement
  81. If you want to assign a value to a name defined at the top level of the program (i.e. not inside
  82. any kind of scope such as functions or classes), then you have to tell Python that the name is not
  83. local, but it is *global*. We do this using the `global` statement. It is impossible to assign a
  84. value to a variable defined outside a function without the `global` statement.
  85. You can use the values of such variables defined outside the function (assuming there is no
  86. variable with the same name within the function). However, this is not encouraged and should be
  87. avoided since it becomes unclear to the reader of the program as to where that variable's
  88. definition is. Using the `global` statement makes it amply clear that the variable is defined in an
  89. outermost block.
  90. Example (save as `function_global.py`):
  91. [source,python]
  92. --------------------------------------------------
  93. include::programs/function_global.py[]
  94. --------------------------------------------------
  95. Output:
  96. --------------------------------------------------
  97. include::programs/function_global.txt[]
  98. --------------------------------------------------
  99. .How It Works
  100. The `global` statement is used to declare that `x` is a global variable - hence, when we assign a
  101. value to `x` inside the function, that change is reflected when we use the value of `x` in the main
  102. block.
  103. You can specify more than one global variable using the same `global` statement e.g. `global x, y,
  104. z`.
  105. [[default_argument_values]]
  106. === Default Argument Values
  107. For some functions, you may want to make some parameters *optional* and use default values in case
  108. the user does not want to provide values for them. This is done with the help of default argument
  109. values. You can specify default argument values for parameters by appending to the parameter name
  110. in the function definition the assignment operator (`=`) followed by the default value.
  111. Note that the default argument value should be a constant. More precisely, the default argument
  112. value should be immutable - this is explained in detail in later chapters. For now, just remember
  113. this.
  114. Example (save as `function_default.py`):
  115. [source,python]
  116. --------------------------------------------------
  117. include::programs/function_default.py[]
  118. --------------------------------------------------
  119. Output:
  120. --------------------------------------------------
  121. include::programs/function_default.txt[]
  122. --------------------------------------------------
  123. .How It Works
  124. The function named `say` is used to print a string as many times as specified. If we don't supply a
  125. value, then by default, the string is printed just once. We achieve this by specifying a default
  126. argument value of `1` to the parameter `times`.
  127. In the first usage of `say`, we supply only the string and it prints the string once. In the second
  128. usage of `say`, we supply both the string and an argument `5` stating that we want to *say* the
  129. string message 5 times.
  130. [CAUTION]
  131. --
  132. Only those parameters which are at the end of the parameter list can be given default argument
  133. values i.e. you cannot have a parameter with a default argument value preceding a parameter without
  134. a default argument value in the function's parameter list.
  135. This is because the values are assigned to the parameters by position. For example,`def func(a,
  136. b=5)` is valid, but `def func(a=5, b)` is *not valid*.
  137. --
  138. [[keyword_arguments]]
  139. === Keyword Arguments
  140. If you have some functions with many parameters and you want to specify only some of them, then you
  141. can give values for such parameters by naming them - this is called *keyword arguments* - we use
  142. the name (keyword) instead of the position (which we have been using all along) to specify the
  143. arguments to the function.
  144. There are two advantages - one, using the function is easier since we do not need to worry about
  145. the order of the arguments. Two, we can give values to only those parameters to which we want to,
  146. provided that the other parameters have default argument values.
  147. Example (save as `function_keyword.py`):
  148. [source,python]
  149. --------------------------------------------------
  150. include::programs/function_keyword.py[]
  151. --------------------------------------------------
  152. Output:
  153. --------------------------------------------------
  154. include::programs/function_keyword.txt[]
  155. --------------------------------------------------
  156. .How It Works
  157. The function named `func` has one parameter without a default argument value, followed by two
  158. parameters with default argument values.
  159. In the first usage, `func(3, 7)`, the parameter `a` gets the value `3`, the parameter `b` gets the
  160. value `7` and `c` gets the default value of `10`.
  161. In the second usage `func(25, c=24)`, the variable `a` gets the value of 25 due to the position of
  162. the argument. Then, the parameter `c` gets the value of `24` due to naming i.e. keyword
  163. arguments. The variable `b` gets the default value of `5`.
  164. In the third usage `func(c=50, a=100)`, we use keyword arguments for all specified values. Notice
  165. that we are specifying the value for parameter `c` before that for `a` even though `a` is defined
  166. before `c` in the function definition.
  167. [[varargs_parameters]]
  168. === VarArgs parameters
  169. Sometimes you might want to define a function that can take _any_ number of parameters,
  170. i.e. **var**iable number of **arg**uments, this can be achieved by using the stars (save as
  171. `function_varargs.py`):
  172. [source,python]
  173. --------------------------------------------------
  174. include::programs/function_varargs.py[]
  175. --------------------------------------------------
  176. Output:
  177. --------------------------------------------------
  178. include::programs/function_varargs.txt[]
  179. --------------------------------------------------
  180. .How It Works
  181. When we declare a starred parameter such as `*param`, then all the positional arguments from that
  182. point till the end are collected as a tuple called 'param'.
  183. Similarly, when we declare a double-starred parameter such as `**param`, then all the keyword
  184. arguments from that point till the end are collected as a dictionary called 'param'.
  185. We will explore tuples and dictionaries in a <<data_structures,later chapter>>.
  186. [[the_return_statement]]
  187. === The +return+ statement
  188. The `return` statement is used to *return* from a function i.e. break out of the function. We can
  189. optionally *return a value* from the function as well.
  190. Example (save as `function_return.py`):
  191. [source,python]
  192. --------------------------------------------------
  193. include::programs/function_return.py[]
  194. --------------------------------------------------
  195. Output:
  196. --------------------------------------------------
  197. include::programs/function_return.txt[]
  198. --------------------------------------------------
  199. .How It Works
  200. The `maximum` function returns the maximum of the parameters, in this case the numbers supplied to
  201. the function. It uses a simple `if..else` statement to find the greater value and then *returns*
  202. that value.
  203. Note that a `return` statement without a value is equivalent to `return None`. `None` is a special
  204. type in Python that represents nothingness. For example, it is used to indicate that a variable has
  205. no value if it has a value of `None`.
  206. Every function implicitly contains a `return None` statement at the end unless you have written
  207. your own `return` statement. You can see this by running `print some_function()` where the function
  208. `some_function` does not use the `return` statement such as:
  209. [source,python]
  210. --------------------------------------------------
  211. def some_function():
  212. pass
  213. --------------------------------------------------
  214. The `pass` statement is used in Python to indicate an empty block of statements.
  215. TIP: There is a built-in function called `max` that already implements the 'find maximum'
  216. functionality, so use this built-in function whenever possible.
  217. [[docstrings]]
  218. === DocStrings
  219. Python has a nifty feature called *documentation strings*, usually referred to by its shorter name
  220. *docstrings*. DocStrings are an important tool that you should make use of since it helps to
  221. document the program better and makes it easier to understand. Amazingly, we can even get the
  222. docstring back from, say a function, when the program is actually running!
  223. Example (save as `function_docstring.py`):
  224. [source,python]
  225. --------------------------------------------------
  226. include::programs/function_docstring.py[]
  227. --------------------------------------------------
  228. Output:
  229. --------------------------------------------------
  230. include::programs/function_docstring.txt[]
  231. --------------------------------------------------
  232. .How It Works
  233. A string on the first logical line of a function is the *docstring* for that function. Note that
  234. DocStrings also apply to <<module,modules>> and <<oop,classes>> which we will learn about in the
  235. respective chapters.
  236. The convention followed for a docstring is a multi-line string where the first line starts with a
  237. capital letter and ends with a dot. Then the second line is blank followed by any detailed
  238. explanation starting from the third line. You are *strongly advised* to follow this convention for
  239. all your docstrings for all your non-trivial functions.
  240. We can access the docstring of the `print_max` function using the `__doc__` (notice the *double
  241. underscores*) attribute (name belonging to) of the function. Just remember that Python treats
  242. *everything* as an object and this includes functions. We'll learn more about objects in the
  243. chapter on <<oop,classes>>.
  244. If you have used `help()` in Python, then you have already seen the
  245. usage of docstrings! What it does is just fetch the `__doc__`
  246. attribute of that function and displays it in a neat manner for
  247. you. You can try it out on the function above - just include `help(print_max)` in your
  248. program. Remember to press the `q` key to exit `help`.
  249. Automated tools can retrieve the documentation from your program in this manner. Therefore, I
  250. *strongly recommend* that you use docstrings for any non-trivial function that you write. The
  251. `pydoc` command that comes with your Python distribution works similarly to `help()` using
  252. docstrings.
  253. === Summary
  254. We have seen so many aspects of functions but note that we still haven't covered all aspects of
  255. them. However, we have already covered most of what you'll use regarding Python functions on an
  256. everyday basis.
  257. Next, we will see how to use as well as create Python modules.