{"id":6057,"date":"2019-08-15T13:51:52","date_gmt":"2019-08-15T13:51:52","guid":{"rendered":"http:\/\/teachcomputerscience.com\/?page_id=6057"},"modified":"2021-01-06T10:05:00","modified_gmt":"2021-01-06T10:05:00","slug":"functions","status":"publish","type":"page","link":"https:\/\/teachcomputerscience.com\/python-resources\/functions\/","title":{"rendered":"Python Functions Tutorial"},"content":{"rendered":"\n<p> As we have seen, loops can help us reuse our code. But what if we want to use the same code in a different part of our program? Do we have to write it again there?<\/p>\n\n\n\n<p>How can we test just one part of our code to make sure it&#8217;s working correctly?<\/p>\n\n\n\n<p>Let&#8217;s learn how to reuse the code we need, whenever and wherever we need it. We&#8217;ll also see a great way to make our code easier to read and understand.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python Functions 1<\/h2>\n\n\n\n<p>Run the example: <\/p>\n\n\n\n<figure><iframe loading=\"lazy\" src=\"https:\/\/trinket.io\/python3\/d1ccef3065\" allowfullscreen=\"\" width=\"100%\" height=\"356\"><\/iframe><\/figure>\n\n\n\n<p><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Question: Nothing happened. What&#8217;s wrong?<\/strong><\/li><li><strong>Answer: <\/strong> If you build a car but you don&#8217;t drive it, it won&#8217;t help you. We&#8217;ve built our function, now we need to use it! <\/li><\/ul>\n\n\n\n<p>Run: <\/p>\n\n\n\n<p><pre>def ask():<br>     print(\"Ya like jazz?\")<br> ask()<\/pre><\/p>\n\n\n\n<p>The last line <strong>calls <\/strong>the function, telling Python to use it! You can call a function as many times as you like. <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python Functions 2<\/h2>\n\n\n\n<p><pre>print()<\/pre>, input(), and range() are all functions we&#8217;ve already seen.<\/p>\n\n\n\n<p>Many times, we put something between the parentheses when we use those functions.&nbsp;<\/p>\n\n\n\n<p>Things we put between the parentheses are called <strong>parameters<\/strong>. One function can take many parameters!<\/p>\n\n\n\n<p>When we make our own functions, we can let them take parameters.<\/p>\n\n\n\n<p>Run:<\/p>\n\n\n\n<p><pre>def count(num):<br> for x in range(1, num + 1):<br>         print(x)<br>         if x == num:<br>               print(\"Done!\")<br> count(10)<\/pre><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python Functions 3<\/h2>\n\n\n\n<p> In the code on the previous page, we defined a function called count that needs a parameter called <pre>num<\/pre>.<\/p>\n\n\n\n<p>Then, we made a for loop and an if statement inside the function.<\/p>\n\n\n\n<p>On the last line, outside the function, we called count() and we gave it the number 10 to work with.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Question:  What does the function do with <\/strong><pre><strong>num<\/strong><\/pre><strong>? <\/strong><\/li><li><strong>Answer: <\/strong>  <pre>num<\/pre> is used to tell Python how many times the for loop will run. Then, we print &#8220;Done!&#8221;, but only if we are on the last time the loop runs. <\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Python Functions 4<\/h2>\n\n\n\n<p> Some functions give us something when they are done running. Isn&#8217;t that nice? This is called <strong>returning<\/strong>. <\/p>\n\n\n\n<p>Run:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def be_honest():\n    print(\"Ooh, I found someone's wallet!\")\n    return \"the wallet\"\nprint( be_honest() )<\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Question:  Why does this code print out &#8220;the wallet&#8221;? <\/strong><\/li><li><strong>Answer: <\/strong> Because that&#8217;s what the function returns. It returns &#8220;the wallet&#8221;! That is, a string that says &#8220;the wallet.&#8221; <\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Python Functions 5<\/h2>\n\n\n\n<p>What if this function is bad and wants to take some money from the wallet? <\/p>\n\n\n\n<p>Run:<\/p>\n\n\n\n<p><pre>money = 5<br> def find_wallet():<br>   money = money - 2<br>   print(\"Ooh, I found someone's wallet!\")<br>   return \"the wallet\"<br> print(find_wallet())<\/pre><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Question:  <\/strong>Why the error? <\/li><li><strong>Answer: <\/strong>  Python doesn&#8217;t realize that when we use the variable <pre>money<\/pre> here, we are talking about the variable we defined outside the function, not the one we defined inside it. Because it&#8217;s confused, it&#8217;s telling us that we can&#8217;t use a variable before we finish assigning it. <\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Python Functions 6<\/h2>\n\n\n\n<p>\nVariables made inside a function, loop, or if statement are <strong>local<\/strong><strong> <\/strong><strong>variables<\/strong>. We can only use them inside their home.<\/p>\n\n\n\n<p>Variables made outside a function are <strong>global variables<\/strong>. We can use them anywhere in the file.<\/p>\n\n\n\n<p>It takes a little bit of work to get around this error, but at least it&#8217;s for a good cause, right?<\/p>\n\n\n\n<p>Run:<\/p>\n\n\n\n<p><pre>money = 5<br>def find_wallet():<br>   print(\"Ooh, I found someone's wallet!\")<br>   return \"the wallet\"<br>def steal(starting_amount, stolen_amount):<br>   print(\"I just stole\", stolen_amount, \"dollars!\")<br>   return starting_amount - stolen_amount<br>money = steal(money, 2)<br>print(find_wallet(), \"was returned with\", money, \"dollars in it.\")<\/pre><\/p>\n\n\n\n<p> There are other ways to get around the problem, but some of them require a more advanced knowledge of Python. Notice the two parameters in the <pre>steal()<\/pre> function! <\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python Functions 7<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">\nActivity:\n\n<\/h3>\n\n\n\n<p>You got in trouble in class again! As a punishment, your teacher is going to make you write some things on the board over and over again until you learn your lesson.<\/p>\n\n\n\n<p>While the teacher isn&#8217;t looking, make a function that writes whatever you need to write, however many times you need to write it.<\/p>\n\n\n\n<p>Starting code:<\/p>\n\n\n\n<p><pre>sentence1 = \"I will not steal wallets.\"<br>sentence2 = \"I will not chew gum in class\"<br>sentence3 = \"I will not stick said gum under the door handle\"<\/pre><\/p>\n\n\n\n<p>An ideal answer: <\/p>\n\n\n\n<p><pre>def write_bot(msg, amnt):<br>   for x in range(1, amnt + 1):<br>     print(msg)<br> write_bot(sentence1, amounts[0])<br> write_bot(sentence2, amounts[1])<br> write_bot(sentence3, amounts[2])<\/pre><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Python Functions 8<\/h2>\n\n\n\n<p><strong>Explanation:<\/strong><\/p>\n\n\n\n<p>We define the sentences and amounts first.<\/p>\n\n\n\n<p>Then, there is a function defined that takes two parameters. The function has a for loop that prints the given sentence the given amount of times.<\/p>\n\n\n\n<p>Finally, we call the function three times, with a different sentence and amount each time. The amounts are given in a list, so students will have to remember how to access list items.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>As we have seen, loops can help us reuse our code. But what if we want to use the same code in a different part of our program? Do we have to write it again there? How can we test just one part of our code to make sure it&#8217;s working correctly? Let&#8217;s learn how &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"Python Functions Tutorial\" class=\"read-more button\" href=\"https:\/\/teachcomputerscience.com\/python-resources\/functions\/\" aria-label=\"More on Python Functions Tutorial\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"parent":6034,"menu_order":8,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_generate-full-width-content":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"tags":[],"class_list":["post-6057","page","type-page","status-publish"],"acf":[],"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/teachcomputerscience.com\/wp-json\/wp\/v2\/pages\/6057","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/teachcomputerscience.com\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/teachcomputerscience.com\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/teachcomputerscience.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/teachcomputerscience.com\/wp-json\/wp\/v2\/comments?post=6057"}],"version-history":[{"count":1,"href":"https:\/\/teachcomputerscience.com\/wp-json\/wp\/v2\/pages\/6057\/revisions"}],"predecessor-version":[{"id":666756,"href":"https:\/\/teachcomputerscience.com\/wp-json\/wp\/v2\/pages\/6057\/revisions\/666756"}],"up":[{"embeddable":true,"href":"https:\/\/teachcomputerscience.com\/wp-json\/wp\/v2\/pages\/6034"}],"wp:attachment":[{"href":"https:\/\/teachcomputerscience.com\/wp-json\/wp\/v2\/media?parent=6057"}],"wp:term":[{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/teachcomputerscience.com\/wp-json\/wp\/v2\/tags?post=6057"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}