{"id":267,"date":"2010-08-30T12:57:20","date_gmt":"2010-08-30T12:57:20","guid":{"rendered":"http:\/\/cemclinux1.math.uwaterloo.ca\/~cscircles\/wordpress\/"},"modified":"2010-08-30T12:57:20","modified_gmt":"2010-08-30T12:57:20","slug":"2-functions","status":"publish","type":"page","link":"https:\/\/olescs.hkmu.edu.hk\/python\/2-functions\/","title":{"rendered":"2: Functions"},"content":{"rendered":"<!-- Please retain this notice and add more notes if you create a new version.<br \/>\nOriginal lesson author: Graeme Kemkes, gdkemkes@alumni.uwaterloo.ca, http:\/\/cscircles.ca<br \/>\nLicense: http:\/\/creativecommons.org\/licenses\/by-nc-sa\/3.0\/-->\n<p>We have seen one function already, <code>print()<\/code>, which outputs a message. To use a function you always write its name, followed by some\u00a0<em>arguments<\/em> in parentheses <code>()<\/code>. The word <em>argument<\/em> basically means an input to the function. Then, the function does some action depending on its arguments. When there are multiple arguments to a function, you separate them with commas (<code>,<\/code>). For example, you can give multiple arguments to <code>print<\/code>; it will print all of them in order, with spaces separating them. We demonstrate in the example below.<br \/>\n<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>Print three numbers<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 58px;'><textarea wrap='off' name='usercode0' id='usercode0'  cols=10 rows=2 readonly='readonly'  style = 'height : 58px;'  class='pyboxCode RO'>\nx = 3\nprint(x, x +   x  , x * x)<\/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<\/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=\"51b3011fc5915e78e76a5018d2450e45\"\/>\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<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> The extra spaces in the sample program above had no effect on the output. Extra spaces are meaningless in most other situations too. However, be careful that <em>extra space at the <strong>beginning<\/strong> of a line<\/em>, called <em>indenting<\/em>, has a special meaning that can <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/console\/?consolecode=print%28%22This%20line%20is%20ok%22%29%0A%20print%28%22This%20one%20starts%20with%20a%20space%22%29\" target=\"_blank\">cause errors (click for an example)<\/a> if used incorrectly. You will see correct indenting a few lessons later. <\/span><\/td><\/table><\/p>\n<p>A function may also give back a value (like an output). For example\u00a0the function <code>max()<\/code> (short for <em>maximum<\/em>) gives back the largest out of all of its arguments, which must be numbers.<br \/>\n<form class=\"pbform\" action=\"#\" id=\"pbform1\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox1'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div><em>Try to predict the output of the following program, before you run it.<\/em><div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 58px;'><textarea wrap='off' name='usercode1' id='usercode1'  cols=10 rows=2 readonly='readonly'  style = 'height : 58px;'  class='pyboxCode RO'>\nprint(max(42, 17))\nprint(max(128,281,812))<\/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<\/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=\"63d7a889992170aa6cb0a32d6c940050\"\/>\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>\nThe name <em>return value<\/em> means the value that a function gives back. For example in <code>max(42, 17)<\/code> we say that \"the function <code>max<\/code> returned the value <code>42<\/code>.\"<\/p>\n<p>The <code>max<\/code> function has a friend which behaves similarly: the <code>min<\/code> function returns the <em>minimum<\/em> (smallest) of its arguments.<\/p>\n<div class='pybox modeNeutral' id='pybox2'>\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'>Min and Max I<\/span><\/div><div>What is the output of the following program? <\/p>\n<pre>x = 13<br\/>y = 7<br\/>a = max(x+y, x*2)<br\/>b = min(x, y)<br\/>print(a,b)<\/pre> <\/div><label>Your choice: <\/label><select id=\"pyselect2\"><option value=\"d\" selected>Select one<\/option><option value=\"w\">13 20<\/option><option value=\"r\">26 7<\/option><option value=\"w\">7 26<\/option><option value=\"w\">20 13<\/option><\/select><div class='pyboxbuttons'><input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" name=\"slug\" value=\"2.intro\"\/><input type='submit' style='margin:5px;' value='Check answer' onClick='pbMultiCheck(2)'\/><\/div><div class=\"pbresults\" id=\"pyMultiResults2\"><\/div><div class=\"epilogue\">Correct!<\/div><\/div>\n<p>Functions can be combined to create more complicated expressions.<br \/>\n<div class='pybox modeNeutral' id='pybox3'>\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'>Short Answer Exercise: <\/span><span class='title'>Min and Max II<\/span><\/div>What is the output of the following program? <a class=\"hintlink\"  id=\"hintlink4\">Hint<\/a> <\/p>\n<pre>x = min(max(13, 7), 9)<br\/>print(x)<\/pre><label for=\"pyShortAnswer3\">Your answer (enter a number): <\/label><input type=\"text\" onkeypress=\"{if (event.keyCode==13) pbShortCheck(3)}\" id=\"pyShortAnswer3\"><div class=\"pyboxbuttons\"><input type=\"hidden\" name=\"type\" value=\"number\"\/><input type=\"hidden\" name=\"correct\" value=\"9\"\/><input type=\"hidden\" name=\"slug\" value=\"2.compose\"\/><input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type='submit' style='margin:5px;' value='Check answer' onClick = 'pbShortCheck(3)'\/><\/div><div class=\"pbresults\" id=\"pyShortResults3\"><\/div><div class=\"epilogue\">Correct!<\/div><\/div>\n<p>You are not limited to using functions that are pre-defined in Python. In a few lessons you will learn how to define new functions!<\/p>\n<h2>Common Errors<\/h2>\n<p>If you call a function with not enough arguments (inputs) or too many arguments, you get an error. For example, <code>max<\/code> requires at least one input:<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform5\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox5'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Calling <code>max<\/code> with too few arguments.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 32px;'><textarea wrap='off' name='usercode5' id='usercode5'  cols=10 rows=1 readonly='readonly'  style = 'height : 32px;'  class='pyboxCode RO'>\nmax()<\/textarea><\/div>\n<div id='pbhistory5' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit5' value=' '\/><\/td>\n<\/tr><\/table><\/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=\"533d15721b982f77f37080b7877c5b1d\"\/>\n<div id='pbresults5' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit5\").value = \"Run program\";document.getElementById(\"inputInUse5\").value = \"N\";<\/script>\n<\/p>\n<p>It's very important to carefully read the errors that you get back, when your code doesn't work. Python will usually give you helpful feedback on what went wrong. However, sometimes you need to look around a little bit to diagnose the problem\u00a0\u2014 here's an example.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform6\" method=\"POST\">\n<div class='pybox modeNeutral  facultative' id='pybox6'>\n<div class=\"heading\"><span class=\"title\">Example<\/span><\/div>Press <strong>Run program<\/strong> and look at the error that occurs.<div class='pyboxTextwrap pyboxCodewrap RO '  style='height: 58px;'><textarea wrap='off' name='usercode6' id='usercode6'  cols=10 rows=2 readonly='readonly'  style = 'height : 58px;'  class='pyboxCode RO'>\nsmaller = min(14, 99\nbigger = max(3, 4)<\/textarea><\/div>\n<div id='pbhistory6' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit6' value=' '\/><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse6\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"6\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"167beb08629b6fed87e7d3a0f4c7393e\"\/>\n<div id='pbresults6' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit6\").value = \"Run program\";document.getElementById(\"inputInUse6\").value = \"N\";<\/script>\n<\/p>\n<p>Python says there is a syntax error, which means it can't understand what you're trying to do:<\/p>\n<pre>\u00a0Traceback (most recent call last):\n   In line 2 of the code you submitted:\n     bigger = max(3, 4)\n          ^\n SyntaxError: invalid syntax<\/pre>However, the line <code>bigger = max(3, 4)<\/code>\u00a0is actually fine. The problem actually spilled over from the previous line: we forgot to add the closing parenthesis <code>)<\/code> after <code>smaller = min(14, 99<\/code> and Python started looking at the next line for the <code>)<\/code>. So, check the lines before and after what Python suggests, if you are stuck debugging your programs.<\/p>\n<h2>Exercise<\/h2>\n<p>This is a two-part exercise using the\u00a0<code>min<\/code>\u00a0and\u00a0<code>max<\/code>\u00a0functions.\u00a0There are connections between the cities of Maxime and Miniac with several bridges. There is a separate limit on the amount of weight that can be transported across each bridge.<\/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'>One Road<\/span><\/div>For part 1, there is a single road between the two cities. The road has three bridges with weight limits\u00a0<code>a<\/code>,\u00a0<code>b<\/code>,\u00a0<code>c<\/code>, as shown in the picture below: <\/p>\n<div><img loading=\"lazy\" decoding=\"async\" src=\"..\/wp-content\/lesson_files\/img\/2\/one-road.png\" alt=\"\" width=\"802\" height=\"296\" \/><\/div>\n<p> In order to drive along the route, your truck needs to drive first over the bridge with weight limit\u00a0<code>a<\/code>, then the one with weight limit\u00a0<code>b<\/code>, then the one with weight limit\u00a0<code>c<\/code>. Your truck will crash if you overload\u00a0<em>any<\/em>\u00a0of the three weight limits. <em>Write a program that prints out the maximum weight that can be transported along this road.<\/em> Your code should assume that the variables\u00a0<code>a<\/code>,\u00a0<code>b<\/code>, and\u00a0<code>c<\/code>\u00a0already contain the bridge weight limits.<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<\/textarea><\/div>\n<div id='pbhistory7' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit7' value=' '\/><\/td>\n<td><input type='button' name='history' value=\"History\" onclick=\"historyClick(7,'2.bridges1')\" ><\/td>\n<td><input type='button' name='help' value=\"Help\" onclick=\"helpClick(7);\" ><\/td>\n<\/tr><\/table><\/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=\"e5e552e11449fe39ef113bfa16bde329\"\/>\n<div id='pbresults7' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit7\").value = \"Run program\";document.getElementById(\"inputInUse7\").value = \"N\";<\/script>\n<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform8\" method=\"POST\">\n<div class='pybox modeNeutral ' id='pybox8'>\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'>Two Roads<\/span><\/div>Part #2: Now we will tell you the whole story. There is also a\u00a0<strong>second route<\/strong>\u00a0consisting of two bridges, the first with weight limit\u00a0<code>d<\/code>, and the second with weight limit\u00a0<code>e<\/code>, as illustrated below. <\/p>\n<div style=\"text-align: center\"><img loading=\"lazy\" decoding=\"async\" src=\"..\/wp-content\/lesson_files\/img\/2\/two-roads.png\" alt=\"\" width=\"737\" height=\"428\" \/><\/div>\n<p> Your truck can take either route. Write a program that prints out the maximum weight that can be transported between the two cities. Assume that the variables\u00a0<code>a<\/code>,\u00a0<code>b<\/code>,\u00a0<code>c<\/code>,\u00a0<code>d<\/code>, and\u00a0<code>e<\/code>\u00a0contain the bridge weight limits. <a class=\"hintlink\"  id=\"hintlink9\">Hint<\/a> <a class=\"hintlink\"  id=\"hintlink10\">Hint 2<\/a>\u00a0<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='usercode8' id='usercode8'  cols=10 rows=20   class='pyboxCode RW'>\n<\/textarea><\/div>\n<div id='pbhistory8' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit8' value=' '\/><\/td>\n<td><input type='button' name='history' value=\"History\" onclick=\"historyClick(8,'2.bridges2')\" ><\/td>\n<td><input type='button' name='help' value=\"Help\" onclick=\"helpClick(8);\" ><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse8\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"8\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"8c4c3aaadd17ae658ddbe8a5bea88b6e\"\/>\n<div id='pbresults8' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit8\").value = \"Run program\";document.getElementById(\"inputInUse8\").value = \"N\";<\/script>\n<\/p>\n<h2>Exercise: Code Scramble<\/h2>\n<p>Here is another code scramble, where you must drag-and-drop the lines to rearrange them into a correct program.<\/p>\n<p><form class=\"pbform\" action=\"#\" id=\"pbform11\" method=\"POST\">\n<div class='pybox modeNeutral scramble' id='pybox11'>\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'>Scramble Exercise: <\/span><span class='title'>Sort of Strangeness<\/span><\/div>Arrange the code so that it prints the\u00a0three numbers\u00a0<code>x<\/code>,\u00a0<code>y<\/code>\u00a0and\u00a0<code>z<\/code>\u00a0<strong>sorted<\/strong>\u00a0in increasing order, so that the smallest is printed first, then the middle one, and then the largest one.<br\/><em>Drag and drop with your mouse to rearrange the lines.<\/em><ul class=\"pyscramble\" name=\"pyscramble\" id=\"pyscramble11\">\n <li class=\"pyscramble\">print(max(x, y, z))<\/li>\n <li class=\"pyscramble\">print(min(x, y, z))<\/li>\n <li class=\"pyscramble\">print(x+y+z-min(x, y, z)-max(x, y, z))<\/li>\n<\/ul>\n<input type='hidden' id='usercode11' name='usercode11'\/>\n<div id='pbhistory11' class='flexcontain' style='display:none;'><\/div>\n<div class='pyboxbuttons'><table><tr>\n<td><input type='submit' name='submit' id='submit11' value=' '\/><\/td>\n<\/tr><\/table><\/div>\n<input type=\"hidden\" name=\"lang\" value=\"en-US\"\/><input type=\"hidden\" id=\"inputInUse11\" name=\"inputInUse\" value=\"Y\"\/>\n<input type=\"hidden\" name=\"pyId\" value=\"11\"\/>\n<input type=\"hidden\" name=\"hash\" value=\"a474c0ccac5da8834e670b784afba050\"\/>\n<div id='pbresults11' class='pbresults'><\/div>\n<\/div>\n<\/form>\n<script type='text\/javascript'>document.getElementById(\"submit11\").value = \"Run program\";document.getElementById(\"inputInUse11\").value = \"N\";<\/script>\n<\/p>\n<p>Once you finish the exercise above, you have two choices:<\/p>\n<ul>\n<li>You can go directly to <a class=\"open-same-window\" href=\"\/3-comments-literals\/\">Lesson 3<\/a>, or<\/li>\n<li>you can do some extra practice exercises about functions in <a class=\"open-same-window\" href=\"\/2x-extra-practice\/\">Lesson 2X<\/a>.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>We have seen one function already, print(), which outputs a message. To use a function you always write its name, followed by some\u00a0arguments in parentheses (). The word argument basically means an input to the function. Then, the function does &hellip; <a href=\"https:\/\/olescs.hkmu.edu.hk\/python\/2-functions\/\">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-267","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/267"}],"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=267"}],"version-history":[{"count":2,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/267\/revisions"}],"predecessor-version":[{"id":11482,"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/pages\/267\/revisions\/11482"}],"wp:attachment":[{"href":"https:\/\/olescs.hkmu.edu.hk\/python\/wp-json\/wp\/v2\/media?parent=267"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}