{"id":1150,"date":"2010-12-12T14:19:34","date_gmt":"2010-12-12T19:19:34","guid":{"rendered":"http:\/\/cemclinux1.math.uwaterloo.ca\/~cscircles\/wordpress\/"},"modified":"2010-12-12T14:19:34","modified_gmt":"2010-12-12T19:19:34","slug":"10-def","status":"publish","type":"page","link":"https:\/\/olescs.hkmu.edu.hk\/python\/10-def\/","title":{"rendered":"10: def"},"content":{"rendered":"<!-- Please retain this notice and add more notes if you create a new version.<br \/>\nOriginal lesson author: David Pritchard, daveagp@gmail.com, http:\/\/cscircles.ca<br \/>\nLicense: http:\/\/creativecommons.org\/licenses\/by-nc-sa\/3.0\/-->\n<p>In this lesson we show you the most important idea in programming: defining your own functions! Functions let your program become shorter, better-organized, easier to read, easier to debug, and more reusable. In later lessons we will see other benefits like <em>recursion<\/em>.<\/p>\n<h1>Defining a Function<\/h1>\n<p>We'll start with an example. Remember the function <code>abs<\/code>? It takes one argument (a number <em>x<\/em>), and returns its absolute value (which is <em>x<\/em> when <em>x <\/em>\u2265 0, and -<em>x<\/em> when <em>x<\/em> &lt; 0). The way to define this function in Python is:<\/p>\n<pre>def abs(x):     # define a function named 'abs' of one argument named 'x'\n  if x &gt;= 0:    # function body starts here\n    return x\n  else:\n    return -x   # function body ends here<\/pre>(Click <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=def%20abs%28x%29%3A%20%23Function%20definition%0A%20%20if%20x%20%26gt%3B%3D%200%3A%0A%20%20%20%20return%20x%0A%20%20else%3A%20%20%0A%20%20%20%20return%20-x%0A%0A%23%20Main%20program%20begins%20here%0Aprint%28abs%28-5%29%29%0Aprint%28abs%2810%29%29\" target=\"_blank\">here<\/a> to test this code in the console.)<\/p>\n<h2>The Two Parts of a Function Definition<\/h2>\n<p>The first line in a function definition specifies the <em>name<\/em> of the function and the <em>arguments<\/em> of the function. It should look like<\/p>\n<p style=\"text-align: center\"><code>def \u00abfunction-name\u00bb(\u00abargument-list\u00bb):<\/code><\/p>\n<p>In the example above, <code>abs<\/code> was the function name, and the argument list was <code>x<\/code>. It is called an <em>argument list<\/em> because there can be multiple arguments such as <code>x, y, z<\/code>; it's also possible to have zero arguments, i.e. an empty list. <strong>The arguments are the input(s) to the function.<\/strong><\/p>\n<p>Everything after the first line of a function definition is the <em>body<\/em> of the function. The body is an indented block of code. Whenever the function is called, the body is executed on those arguments\/inputs. Finally, when we reach this line in the function body,<\/p>\n<p style=\"text-align: center\"><code>return \u00abvalue\u00bb<\/code><\/p>\n<p>the function stops running and returns <code>\u00abvalue\u00bb<\/code> as its output<strong>. That is, <\/strong><strong>the return value is the output of the function.<\/strong>\u00a0As the <code>abs<\/code> example shows, the body may contain several <code>return<\/code> statements; but only the first one executed has an effect since the function stops executing afterwards.<\/p>\n<h2>Example: Defining and Calling a Function<\/h2>\n<p>The following program contains a function definition and some other statements that are executed after the function is defined. Can you guess what the output will be?<\/p>\n<p><iframe width='100%' height='480' frameborder='0' scrolling='no' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/OnlinePythonTutor3-cemc\/iframe-embed.html#code=def+square%28x%29%3A+++++%23+function+definition%0A++++return+x%2Ax+++++%23+body+only+has+one+line%0A%0A%23+use+the+function%2C+now+that+it%27s+defined%0Aprint%28square%2810%29%29++++++++%0Aprint%28square%28square%282%29%29%29&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines&width=460&rightStdout=1'><\/iframe><\/p>\n<p>We see that the function name is <code>square<\/code>, there is just one argument <code>x<\/code>, and that the function body consists of just one line <code>return x*x<\/code>. Then outside of the function we have two commands, which call the function a total of three times.<\/p>\n<p>As the visualizer shows, note that a separate chunk of working space (a\u00a0<strong>frame<\/strong>) is allocated each time the function is called. Once the function returns, that working space is no longer needed, and erased.<\/p>\n<p>Here are the steps explained in words:<\/p>\n<ol>\n<li>When the first command is executed, Python must evaluate <code>square(10)<\/code>.\n<ul>\n<li>Python compares the list of inputs <code>(10)<\/code> to the argument list <code>(x)<\/code>. So, it executes the function body <code>return x*x<\/code> while remembering that <code>x<\/code> equals <code>10<\/code>. Thus <code>x*x<\/code> yields <code>100<\/code>, which is printed.<\/li>\n<\/ul>\n<\/li>\n<li>When the second command is executed, Python must evaluate <code>square(square(2))<\/code>.\n<ul>\n<li>The inner part <code>square(2)<\/code> is evaluated first. We temporarily set <code>x<\/code> equal to <code>2<\/code> and run the function body, which returns <code>4<\/code>.<\/li>\n<li>Then the outer expression is evaluated; since <code>square(2)<\/code> gave <code>4<\/code>, we are now calling <code>square(4)<\/code>. This returns <code>16<\/code>, which is printed.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<h2>Four Common Mistakes<\/h2>\n<p>One common mistake you can make in defining a function is to forget the\u00a0<code>return<\/code> statement.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform0\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox0'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Mistake 1: forgetting to <code>return<\/code><div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 84px;'><textarea wrap='off' name='usercode0' id='usercode0'  cols=10 rows=3 readonly='readonly'  style = 'height : 84px;'  class='pyboxCode RO'>\ndef square(x):\n  x*x\nprint(square(10))<\/textarea><\/div>\n<div id='pbhistory0' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit0' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(0)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(0,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse0\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"0\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"d401a99df9d67e64488be6a811464442\"\/>\n<div id='pbresults0' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit0\").value = \"Run program\";document.getElementById(\"inputInUse0\").value = \"N\";<\/script>\n<\/p>\n<p>As you can see, if no <code>return<\/code> statement is encountered in the body, then the function gives <code>None<\/code>\u00a0by default. So, if you are failing some exercise because a function is returning <code>None<\/code>, the problem is often that some function inputs are not causing a <code>return<\/code> statement to be executed.<\/p>\n<p><table class='pywarn'><tr><td class='pywarnleft'><img src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/warning.png'\/><\/td><td class='pywarnright'><span> You may also intentionally omit a <code>return<\/code> statement. This only makes sense if your function has some side effect other than its return value, for example printing some output:<form class=\"pbform\" action=\"#\" id=\"pbform1\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox1'>\n<div class=\"heading\"><span class='type'>Example: <\/span><span class='title'>A side effect and no return statement<\/span><\/div> <div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 136px;'><textarea wrap='off' name='usercode1' id='usercode1'  cols=10 rows=5 readonly='readonly'  style = 'height : 136px;'  class='pyboxCode RO'>\ndef repeatedPrint(string, repetitions):   # no returns in this function\n  for i in range(0, repetitions):\n    print(string)\n\nrepeatedPrint('Hello, world!', 3)<\/textarea><\/div>\n<div id='pbhistory1' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit1' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(1)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(1,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse1\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"1\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"d533b544a0b98dd40c405c9ead5c16ca\"\/>\n<div id='pbresults1' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit1\").value = \"Run program\";document.getElementById(\"inputInUse1\").value = \"N\";<\/script>\n  <\/span><\/td><\/table><\/p>\n<p>Another common mistake is forgetting to indent the code, resulting in an <code>IndentationError<\/code>.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform2\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox2'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Mistake 2: forgetting to indent<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 84px;'><textarea wrap='off' name='usercode2' id='usercode2'  cols=10 rows=3 readonly='readonly'  style = 'height : 84px;'  class='pyboxCode RO'>\ndef square(x):\nreturn x*x\nprint(square(10))<\/textarea><\/div>\n<div id='pbhistory2' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit2' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(2)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(2,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse2\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"2\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"76a9707ae41952893106ccb9765ef1ba\"\/>\n<div id='pbresults2' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit2\").value = \"Run program\";document.getElementById(\"inputInUse2\").value = \"N\";<\/script>\n<\/p>\n<p>As we saw in lesson 2, calling with too few or too many arguments causes an error.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform3\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox3'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Mistake 3: call with too many arguments<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 84px;'><textarea wrap='off' name='usercode3' id='usercode3'  cols=10 rows=3 readonly='readonly'  style = 'height : 84px;'  class='pyboxCode RO'>\ndef square(x):\n  return x*x\nprint(square(7, 11))<\/textarea><\/div>\n<div id='pbhistory3' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit3' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(3)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(3,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse3\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"3\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"f5b2120c0fc6ad7f25132dea204179c4\"\/>\n<div id='pbresults3' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit3\").value = \"Run program\";document.getElementById(\"inputInUse3\").value = \"N\";<\/script>\n<\/p>\n<p>Finally, if you make a typo when defining or calling the function, you will get an error saying that the function is undefined.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform4\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox4'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Mistake 4: wrong name<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 84px;'><textarea wrap='off' name='usercode4' id='usercode4'  cols=10 rows=3 readonly='readonly'  style = 'height : 84px;'  class='pyboxCode RO'>\ndef square(x):\n  return x*x\nprint(skware(10))<\/textarea><\/div>\n<div id='pbhistory4' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit4' value=' '\/><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(4)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(4,'N')\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse4\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"4\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"5155fcb74e9e404c28b06beff82cd471\"\/>\n<div id='pbresults4' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit4\").value = \"Run program\";document.getElementById(\"inputInUse4\").value = \"N\";<\/script>\n<\/p>\n<h2>Try it Yourself<\/h2>\n<p><table class='pywarn'><tr><td class='pywarnleft'><img src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/warning.png'\/><\/td><td class='pywarnright'><span> There's no need to use <code>input()<\/code> or <code>print()<\/code> for this exercise, or for future exercises where you're asked to \"define a function.\" The grader will <i>call<\/i> your function with arguments automatically, and inspect the result it <i>returns<\/i> directly. <\/p>\n<p>A correct solution for this particular exercise will be 2 lines (see the 'The Two Parts of a Function Definition' at the top of the lesson). <\/span><\/td><\/table><\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform5\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox5'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'>Cubism<\/span><\/div>Define a function\u00a0<code>cube(n)<\/code>, which takes a single number\u00a0<code>n<\/code>\u00a0as input, and outputs its cube\u00a0<code>n<\/code>\u00a0\u00d7\u00a0<code>n<\/code>\u00a0\u00d7\u00a0<code>n<\/code>.<div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode5' id='usercode5'  cols=10 rows=20   class='pyboxCode RW'>\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory5' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput5\">Enter testing statements like <code>print(myfunction(\"test argument\"))<\/code> below.<div class=\"pyboxTextwrap resizy\" style=\"height: 102px;\" ><textarea wrap=\"off\" name=\"userinput\" class=\"pyboxInput\" cols=10 rows=4><\/textarea><\/div><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit5' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch5\" value=\"Input Switch\" onclick=\"pbInputSwitch(5,'Y')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(5)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(5,'Y')\" ><\/td>\n<\/tr><\/table><select id='pbSelect5' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(5,'10.cube')\" >History<\/option>\n<option name='help' data-pbonclick=\"helpClick(5);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse5\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"5\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"72d514655d307489b0eb30eec6d6852e\"\/>\n<div id='pbresults5' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>jQuery(function(){pbToggleCodeMirror(5);});pbInputSwitch(5,\"Y\");<\/script>\n<\/p>\n<h2>Two or More Arguments<img decoding=\"async\" class=\"alignright\" src=\"..\/wp-content\/lesson_files\/img\/10\/area-triangle.png\" alt=\"\" \/><\/h2>\n<p>The functions above only took one argument, but a function can be designed to take any number of arguments. For example, you have been calling\u00a0<code>input()<\/code> with 0 arguments (and you'll define a function with zero arguments in lesson 15A).<\/p>\n<p>Here's an example with <strong>two arguments<\/strong>, about geometry. Suppose we need a function to compute the area of a triangle, given the length of its base and its height. The formula for the area is<\/p>\n<p style=\"text-align: center\">area = base \u00d7 height \/ 2<\/p>\n<p>In code, this looks like the following: we replace\u00a0<code>def \u00abfunction-name\u00bb(\u00abargument1\u00bb)<\/code>\u00a0with\u00a0<code>def \u00abfunction-name\u00bb(\u00abargument1\u00bb, \u00abargument2\u00bb)<\/code>.<\/p>\n<p><iframe width='100%' height='480' frameborder='0' scrolling='no' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/OnlinePythonTutor3-cemc\/iframe-embed.html#code=def+triangleArea%28base%2C+height%29%3A%0A++return+base%2Aheight%2F2%0Aprint%28triangleArea%283%2C+5%29%29%0Aprint%28triangleArea%284%2C+2%29%29&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines&width=345&rightStdout=1'><\/iframe><\/p>\n<p>Another important thing to note is that when a function is\u00a0<em>defined<\/em>\u00a0is different from when the function is\u00a0<em>executed<\/em>. The body doesn't run until the function is actually called. To test this, complete the following exercise:<\/p>\n<div class='pybox modeNeutral' id='pybox6'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Multiple Choice Exercise: <\/span><span class='title'>In-n-Out<\/span><\/div><div> What is the output of the following program? <\/p>\n<pre>def f():          # function of 0 arguments<br\/>   print(\"in f\")<br\/>print(\"not in f\")<br\/>f()               # call f now<\/pre> <\/div><label>Your choice: <\/label><select id=\"pyselect6\"><option value=\"d\" selected>Select one<\/option><option value=\"w\">2 lines: 'in f', then 'not in f'<\/option><option value=\"w\">3 lines: 'in f', then 'not in f', then 'in f'<\/option><option value=\"r\">2 lines: 'not in f', then 'in f'<\/option><\/select><div class='pyboxbuttons'><input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" name=\"slug\" value=\"10.order\"\/><input type='submit' style='margin:5px;' value='Check answer' onClick='pbMultiCheck(6)'\/><\/div><div class=\"pbresults\" id=\"pyMultiResults6\"><\/div><div class=\"epilogue\">Correct! The function <code>f<\/code> is defined first of all, but its body is not executed immediately. After the function is defined we print out <code>not in f<\/code>. Then the function is called, and the body is executed, printing <code>in f<\/code>.<\/div><\/div>\n<p><img decoding=\"async\" class=\"alignright\" style=\"color: #333333;font-style: normal;line-height: 24px;margin-top: 0.4em\" src=\"..\/wp-content\/lesson_files\/img\/10\/peri-rect.png\" alt=\"\" \/><\/p>\n<p>In the last exercise we ask you to write your own function of two arguments, to compute the perimeter of a rectangle. (The perimeter is the total length of all sides.) In a rectangle with a given width and height, its perimeter is given by the following formula:<\/p>\n<p style=\"text-align: center\"><img src='https:\/\/s0.wp.com\/latex.php?latex=%5Ctextrm%7Bperimeter+%3D+width+%2B+height+%2B+width+%2B+height%7D&#038;bg=T&#038;fg=000000&#038;s=2' alt='\\textrm{perimeter = width + height + width + height}' title='\\textrm{perimeter = width + height + width + height}' class='latex' \/><\/p>\n<p style=\"text-align: left\">See the diagram at right for an example.<\/p>\n<p style=\"text-align: left\"><br\/> <br\/><\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform7\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox7'>\n<img title='You have not yet completed this problem.' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/icon.png' class='pycheck'\/><div class=\"heading\"><span class='type'>Coding Exercise: <\/span><span class='title'>Rectangle<\/span><\/div>Define a function\u00a0<code>rectanglePerimeter(width, height)<\/code>\u00a0that computes the perimeter of a rectangle. <div class=\"helpOuter\" style=\"display: none;\"><div class=\"helpInner\"><div style=\"text-align: center\">You need to create an account and log in to ask a question.<\/div><\/div><\/div><div class='pyboxTextwrap pyboxCodewrap RW resizy'  style='height: 526px;'><textarea wrap='off' name='usercode7' id='usercode7'  cols=10 rows=20   class='pyboxCode RW'>\n# delete this comment and enter your code here\n<\/textarea><\/div>\n<div id='pbhistory7' class='flexcontain' style='display:none;'><\/div>\n<div name=\"pyinput\" id=\"pyinput7\">Enter testing statements like <code>print(myfunction(\"test argument\"))<\/code> below.<div class=\"pyboxTextwrap resizy\" style=\"height: 102px;\" ><textarea wrap=\"off\" name=\"userinput\" class=\"pyboxInput\" cols=10 rows=4><\/textarea><\/div><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit7' value=' '\/><\/td>\n<td><input type='button' name='switch' id=\"switch7\" value=\"Input Switch\" onclick=\"pbInputSwitch(7,'Y')\" ><\/td>\n<td><input type='button' name='consolecopy' value=\"Open in console\" onclick=\"pbConsoleCopy(7)\" ><\/td>\n<td><input type='button' name='visualize' value=\"Visualize\" onclick=\"pbVisualize(7,'Y')\" ><\/td>\n<\/tr><\/table><select id='pbSelect7' class='selectmore'><option name='more'>More actions...<\/option>\n<option name='history' data-pbonclick=\"historyClick(7,'10.rectangle')\" >History<\/option>\n<option name='help' data-pbonclick=\"helpClick(7);\" >Help<\/option>\n<\/select><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse7\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"7\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"e8f7d1054e7d5bc2c173b9a13270ec81\"\/>\n<div id='pbresults7' class='pbresults avoidline'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>jQuery(function(){pbToggleCodeMirror(7);});pbInputSwitch(7,\"Y\");<\/script>\n<\/p>\n<h3>Functions Calling Functions<\/h3>\n<p>Functions are the building blocks of well-built large programs: you can do the same task twice without writing out the same code twice, and you can re-use solutions to common tasks. Here is an example of building one function and using it inside of another one.<\/p>\n<p><table class='pywarn'><tr><td class='pywarnleft'><img src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/files\/warning.png'\/><\/td><td class='pywarnright'><span> <em>Can you guess what this program does, before you run it?\u00a0<\/em>Remember from lesson 4 that multiplication of strings and integers means to repeat the string that many times. For example,\u00a0<code>\"tar\"*2<\/code>\u00a0is\u00a0<code>\"tartar\"<\/code>. <\/span><\/td><\/table><\/p>\n<p><em id=\"funcfunc\">Drag the vertical gray line left and right to change how much code &amp; visualization is shown.<\/em><\/p>\n<p><iframe width='100%' height='480' frameborder='0' scrolling='no' src='https:\/\/olescs.hkmu.edu.hk\/python\/wp-content\/plugins\/pybox\/OnlinePythonTutor3-cemc\/iframe-embed.html#code=def+inner%28string%2C+width%29%3A%0A++return+string+%2B+%22+%22+%2A+%28width+-+len%28string%29%29%0A%0Adef+outer%28string1%2C+string2%29%3A%0A++w+%3D+max%28len%28string1%29%2C+len%28string2%29%29%0A++print%28%22%2A%22+%2A+%28w+%2B+4%29%29%0A++print%28%22%2A+%22+%2B+inner%28string1%2C+w%29+%2B+%22+%2A%22%29%0A++print%28%22%2A+%22+%2B+inner%28string2%2C+w%29+%2B+%22+%2A%22%29%0A++print%28%22%2A%22+%2A+%28w+%2B+4%29%29%0A%0Aouter%28%22Box+number+one%22%2C+%22is+very+fun%22%29%0Aouter%28%22Box+%232%22%2C+%22%28not+False%29+is+%22+%2B+str%28not+False%29%29&cumulative=false&heapPrimitives=false&drawParentPointers=false&textReferences=false&showOnlyOutputs=false&py=3&curInstr=0&resizeContainer=true&highlightLines&width=400&rightStdout=1'><\/iframe><\/p>\n<p>You can see a new phenomenon in the visualization: under the \"Frames\"\u00a0column, when we are at Step 8 of 30 in the execution, there are not only\u00a0some global variables, but two frames (one for <code>outer<\/code>, and one for <code>inner<\/code> that was just created). The <code>outer<\/code> one stays waiting until the <code>inner<\/code> one is completely finished, then the <code>outer<\/code> one resumes. It happens to make another call to <code>inner<\/code>, and again <code>outer<\/code> waits; and when <code>inner<\/code> is finished, then <code>outer<\/code> continues to completion. Finally, we call <code>outer<\/code> and the whole process is repeated.<\/p>\n<p>You are now ready for the next lesson!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this lesson we show you the most important idea in programming: defining your own functions! Functions let your program become shorter, better-organized, easier to read, easier to debug, and more reusable. In later lessons we will see other benefits &hellip; <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/10-def\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":0,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1150","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/1150"}],"collection":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/comments?post=1150"}],"version-history":[{"count":1,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/1150\/revisions"}],"predecessor-version":[{"id":11481,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/1150\/revisions\/11481"}],"wp:attachment":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/media?parent=1150"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}