{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Note: You can explore the [associated workbook](https://mybinder.org/v2/gh/melaniewalsh/Intro-Cultural-Analytics/master?urlpath=lab/tree/book/02-Python/Workbooks/12.5-Functions-WORKBOOK.ipynb) for this chapter in the cloud.*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A *function* is way of bundling up code to perform specific tasks. It's kind of like making a little Python wind-up toy that runs on command.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Functions are useful because they can help make your code more organized and save you from repetition. If you have to do some task over and over again, you don't want to write out the same code over and over again from scratch. \n", "\n", "We've encountered built-in Python functions many times already, including:\n", "- `print()`\n", "- `len()`\n", "- `type()` \n", "\n", "These functions contain bundled up code that perform specific tasks whenever we call them." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Define a Function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To make your own function, you use the keyword `def`, short for *define*, followed by your desired name for the function, parentheses (`()`) and a colon (`:`).\n", "\n", "Then, on the following lines, you indent one tab over and write some code that you want your function to perform. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def sing_beyonce_lyrics():\n", " print(\"Okay, okay, ladies, now let's get in formation, 'cause I slay\")\n", " print(\"Okay, ladies, now let's get in formation, 'cause I slay\")\n", " print(\"Prove to me you got some coordination, 'cause I slay\")\n", " print(\"Slay trick, or you get eliminated\")\n", " return " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, you complete the function with a `return` statement. Sometimes you will want to `return` a specific value but here we're not returning anything." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you don't indent the line following the definition of the function, you will get an error. Behold the importance of the indent:" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "ename": "IndentationError", "evalue": "expected an indented block (, line 2)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m print(\"Okay, okay, ladies, now let's get in formation, 'cause I slay\")\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n" ] } ], "source": [ "def sing_beyonce_lyrics():\n", "print(\"Okay, okay, ladies, now let's get in formation, 'cause I slay\")\n", "print(\"Okay, ladies, now let's get in formation, 'cause I slay\")\n", "print(\"Prove to me you got some coordination, 'cause I slay\")\n", "print(\"Slay trick, or you get eliminated\")\n", " return " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Call a Function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To use or \"call\" a function, you simply type the name of the function with parentheses." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Okay, okay, ladies, now let's get in formation, 'cause I slay\n", "Okay, ladies, now let's get in formation, 'cause I slay\n", "Prove to me you got some coordination, 'cause I slay\n", "Slay trick, or you get eliminated\n" ] } ], "source": [ "sing_beyonce_lyrics()" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "def sing_happy_birthday():\n", " print(\"Happy Birthday to you\")\n", " print(\"Happy Birthday to you\")\n", " print(\"Happy Birthday dear human life form\")\n", " print(\"Happy Birthday to you\")\n", " return " ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Happy Birthday to you\n", "Happy Birthday to you\n", "Happy Birthday dear human life form\n", "Happy Birthday to you\n" ] } ], "source": [ "sing_happy_birthday()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add Parameters/Arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can add \"parameters\" to your functions—or values that are required by your function—by putting parameter names inside the parentheses.\n", "\n", "For example, if we want to personalize our birthday song function to include a specific person's name, we can add the parameter `personalized_name` inside the parentheses, which will require a personalized name to be passed to the function. The thing you pass to the function is called an \"argument.\" \n", "\n", "- parameter = `personalized_name` (thing that requires a value for the function) \n", "- argument = \"Beyonce\" (actual value passed to function)\n", "\n", "Since parameters and arguments are so interrelated, they're sometimes confused for each other. You can read [Python's official distinction here](https://docs.python.org/3.3/faq/programming.html#faq-argument-vs-parameter)." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "def sing_personalized_happy_birthday(personalized_name):\n", " print(\"Happy Birthday to you\")\n", " print(\"Happy Birthday to you\")\n", " print(f\"Happy Birthday dear {personalized_name}\")\n", " print(\"Happy Birthday to you\")\n", " return " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We're using whatever name gets passed to the function inside an f-string: `f\"Happy Birthday dear {personalized_name}\"`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once you set a parameter that requires an argument, you have to pass something inside the function for the function to run. So if we run `sing_personalized_happy_birthday()` as we did with `sing_happy_birthday()`, it won't work." ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "sing_personalized_happy_birthday() missing 1 required positional argument: 'name'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0msing_personalized_happy_birthday\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: sing_personalized_happy_birthday() missing 1 required positional argument: 'name'" ] } ], "source": [ "sing_personalized_happy_birthday()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This error is telling us that we have to pass in a value or \"argument.\"" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Happy Birthday to you\n", "Happy Birthday to you\n", "Happy Birthday dear Beyonce\n", "Happy Birthday to you\n" ] } ], "source": [ "sing_personalized_happy_birthday(\"Beyonce\")" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Happy Birthday to you\n", "Happy Birthday to you\n", "Happy Birthday dear Carly Rae Jepsen\n", "Happy Birthday to you\n" ] } ], "source": [ "sing_personalized_happy_birthday(\"Carly Rae Jepsen\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sing_personalized_happy_birthday(#Insert Your Name Here)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Keyword Arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There's another way that you can require arguments in a function, which is with *keyword arguments*. Before we were using \"positional arguments,\" where the function automatically knew that \"Beyonce\" was the `personalized_name` argument simply because \"Beyonce\" was in the right position. (There was only one argument required, so, duh.)\n", "\n", "But you can also explicitly define your arguments with keyword arguments that use an `=` sign, which can become more useful if you have multiple parameters. This can also be a way of setting default values in your functions." ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [], "source": [ "def sing_keyword_happy_birthday(to_name='Beyonce', from_name='Info 1350'):\n", " print(\"Happy Birthday to you\")\n", " print(\"Happy Birthday to you\")\n", " print(f\"Happy Birthday dear {to_name}\")\n", " print(\"Happy Birthday to you\")\n", " print(f\"\\nSincerely, \\n{from_name}\")\n", " return " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For example, if we don't pass in any arguments into this function, it will use the default arguments." ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Happy Birthday to you\n", "Happy Birthday to you\n", "Happy Birthday dear Beyonce\n", "Happy Birthday to you\n", "\n", "Sincerely, \n", "Info 1350\n" ] } ], "source": [ "sing_keyword_happy_birthday()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But if we set the keyword arguments to different values—even if we switch the order or position of the arguments!—the function will know which arguments they're supposed to be." ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Happy Birthday to you\n", "Happy Birthday to you\n", "Happy Birthday dear Cookie Monster\n", "Happy Birthday to you\n", "\n", "Sincerely, \n", "Big Bird\n" ] } ], "source": [ "sing_keyword_happy_birthday(from_name=\"Big Bird\", to_name=\"Cookie Monster\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Return Values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In all of the examples above, we weren't returning any specific value, just using `print()` statements. But sometimes you want a specific value out of your function. For example, if we want to make a function that transforms a bit of text into very loud-sounding text, then we'll want to `return` that loud-sounding text." ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [], "source": [ "def make_text_shouty(text):\n", " shouty_text = text.upper()\n", " return shouty_text" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I LIKE TACOS'" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "make_text_shouty(\"I like tacos\")" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [], "source": [ "def make_text_shoutier(text):\n", " shouty_text = text.upper()\n", " shoutier_text = shouty_text + '!!!'\n", " return shoutier_text" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I LIKE TACOS!!!'" ] }, "execution_count": 80, "metadata": {}, "output_type": "execute_result" } ], "source": [ "make_text_shoutier(\"I like tacos\")" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [], "source": [ "def calculate_dog_years_age(age):\n", " dog_years_age = age * 7\n", " return dog_years_age" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "364" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "calculate_dog_years_age(52)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Your Turn!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Make a function called `make_text_whispery` that transforms text to lower case" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Your Code Here\n", " whispery_text = #Your Code Here\n", " return #Your Code Here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now insert the string \"I AM WHISPERING\" into `make_text_whispery`" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'i am whispering'" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "#Your Code Here" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" } }, "nbformat": 4, "nbformat_minor": 4 }