{ "cells": [ { "cell_type": "markdown", "id": "ceramic-hygiene", "metadata": {}, "source": [ "\n", "\n", "\n", "

Python Programming: Functions

\n", "\n", "\n", "\n", "\n", "---\n", "\n", "## Learning Objectives\n", "*After this lesson, you will be able to...*\n", "\n", "- Identify when to use a function.\n", "- Create and call a function with arguments.\n", "- Return a value from a function.\n", "\n", "---\n", "\n", "## Let's Consider a Repetitive program...\n", "\n", "Consider a program that prints a $5 shipping charge for products on a website:\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "strange-auction", "metadata": {}, "outputs": [], "source": [ "print(\"You've purchased a Hanging Planter.\")\n", "print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")\n", "\n", "# 10 minutes later...\n", "print(\"You've purchased a Shell Mirror.\")\n", "print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")\n", "\n", "# 5 minutes later...\n", "print(\"You've purchased a Modern Shag Rug.\")\n", "print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")" ] }, { "cell_type": "markdown", "id": "mediterranean-amount", "metadata": {}, "source": [ "\n", "What if there are 1,000 orders?\n", "\n", "---\n", "\n", "## Functions\n", "\n", "We can write a **function** to print the order.\n", "\n", "A function is simple — it's a reusable piece of code. We only define it once. Later, we can use its name as a shortcut to run that whole chunk of code.\n", "\n", "* Functions are defined using the `def` syntax.\n", " * `def` stands for \"define.\"\n", "* In this case, we're *defining* a function named 'function_name.'\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "daily-noise", "metadata": {}, "outputs": [], "source": [ "def function_name():\n", " # What you want the function to do\n", " pass\n", "\n", "# Call the function by name to run it:\n", "function_name()\n", "\n", "# 10 minutes later...\n", "function_name()" ] }, { "cell_type": "markdown", "id": "annoying-things", "metadata": {}, "source": [ "\n", "**Protip:** Don't forget the `()`, and be sure to indent!\n", "\n", "---\n", "\n", "## Seeing Functions in Action\n", "\n", "So we *define* the function, then we can *call* the function by pairing its name with the parentheses: `print_order()`." ] }, { "cell_type": "code", "execution_count": null, "id": "manufactured-boutique", "metadata": {}, "outputs": [], "source": [ "def print_order():\n", " print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")\n", "\n", "print(\"You've purchased a Hanging Planter.\")\n", "print_order()" ] }, { "cell_type": "markdown", "id": "supposed-alabama", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## Naming a Function\n", "\n", "What can you name a function?\n", "- Anything you'd like.\n", " - But match the intention and the *invocation*!\n", "- Using `print_order` is more descriptive.\n", "\n", "What do you think will happen if you change the function name `print_order` to `finishedOrder` without updating the invocation?" ] }, { "cell_type": "code", "execution_count": null, "id": "attended-friendship", "metadata": {}, "outputs": [], "source": [ "del print_order\n", "\n", "def finished_order():\n", " print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")\n", " \n", "print(\"You've purchased a Hanging Planter.\")\n", "print_order()\n" ] }, { "cell_type": "markdown", "id": "suspended-failure", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## Multi-Line Functions\n", "\n", "\n", "How many lines of code can a function have?\n", "- As many lines of code as you'd like!\n", "- Just indent each line.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "gorgeous-failure", "metadata": {}, "outputs": [], "source": [ "def welcome():\n", " print(\"Hello!\")\n", " print(\"Bonjour!\")\n", "\n", "welcome()" ] }, { "cell_type": "markdown", "id": "attached-publicity", "metadata": {}, "source": [ "\n", "---\n", "\n", "## We Do: Writing a Function\n", "\n", "Let's make this a little more complicated.\n", "\n", "Let's write a function together, `high_low`, that prints \"High!\" if a variable `my_number` is greater than 10 and \"Low!\" if it isn't." ] }, { "cell_type": "code", "execution_count": null, "id": "italian-statistics", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "governmental-conclusion", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## You Do: FizzBuzz\n", "\n", "This is a *very* common programming question. It's often on job interviews and a buzzword in the industry as a simple but common task to show your understanding.\n", "\n", "- Write a function that prints the numbers from 1 to 101.\n", "- But, for multiples of three, print “Fizz” instead of the number.\n", "- For multiples of five, print “Buzz”.\n", "- For numbers which are multiples of both three and five, print “FizzBuzz”.\n", "- Don't forget to call the function!\n", "\n", "_Hint: think carefully about the order of your conditionals._" ] }, { "cell_type": "code", "execution_count": null, "id": "blessed-happiness", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "banner-conclusion", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## Quick Review: Functions\n", "\n", "Functions are reusable chunks of code. They can have anything in them.\n", "\n", "* Define functions using the `def` keyword.\n", "* A function must be **called** before the code in it will run!\n", "* You will recognize function calls by the `()` at the end.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "balanced-force", "metadata": {}, "outputs": [], "source": [ "# This part is the function definition!\n", "def say_hello():\n", " print(\"hello world!\")\n", "\n", "# This part is actually calling/running the function!\n", "say_hello()\n" ] }, { "cell_type": "markdown", "id": "premier-stomach", "metadata": {}, "source": [ "\n", "You can call them as many times as you'd like, but they need to be defined above the code where you call them.\n", "\n", "Up next: Parameters!\n", "\n", "---\n", "\n", "\n", "## Discussion: Parameters\n", "\n", "\n", "Remember this?\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "adjustable-permit", "metadata": {}, "outputs": [], "source": [ "def print_order():\n", " print(\"Thank you for your order. There will be a $5.00 shipping charge for this order.\")\n", "\n", "print(\"You've purchased a Hanging Planter.\")\n", "print_order()\n", "\n", "print(\"You've purchased a Shell Mirror.\")\n", "print_order()\n", "\n", "print(\"You've purchased a Modern Shag Rug.\")\n", "print_order()" ] }, { "cell_type": "markdown", "id": "nominated-anime", "metadata": {}, "source": [ "\n", "There's still repetition. How do you think we could improve it?\n", "\n", "---\n", "\n", "## Addressing the repetition\n", "\n", "We can dynamically pass a function values. This is a **parameter**.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "loved-arthur", "metadata": {}, "outputs": [], "source": [ "def print_order(product):\n", " print(f\"Thank you for ordering the {product}.\")\n", "\n", "print_order(\"Hanging Planter\")\n", "# Prints \"Thank you for ordering the Hanging Planter.\"\n", "print_order(\"Shell Mirror\")\n", "# Prints \"Thank you for ordering the Shell Mirror.\"\n", "print_order(\"Modern Shag Rug\")\n", "# Prints \"Thank you for ordering the Modern Shag Rug.\"" ] }, { "cell_type": "markdown", "id": "several-suspension", "metadata": {}, "source": [ "\n", "\n", "\n", "---\n", "\n", "## Quick Review: Functions with Parameters\n", "\n", "**Parameter:** The variable that's defined in a function's declaration.\n", "\n", "**Argument:** The actual value passed into the function when the function is called.\n", "\n", "Order matters!\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "broke-shield", "metadata": {}, "outputs": [], "source": [ "def do_something(parameter1, parameter2):\n", " # Does something.\n", "\n", "do_something(argument1, argument2)\n", "do_something(a_different_a" ] }, { "cell_type": "markdown", "id": "polar-confusion", "metadata": {}, "source": [ "\n", "Next up: Returns.\n", "\n", "---\n", "\n", "## The Return\n", "\n", "Sometimes, we want values *back* from functions.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "tender-cache", "metadata": {}, "outputs": [], "source": [ "def calculate_total(price, taxes):\n", " total_amount = price + (price * taxes)\n", " print('The total is $', total_amount)\n", " # Send the total_amount for the drink back to the main program.\n", " return total_amount\n", "\n", "# This just calls the function - we've seen this.\n", "calculate_total(5.5, .10)\n", "\n", "# This is new! Save the amount of this drink into a variable \"latte_total.\"\n", "latte_total = calculate_total(5.5, .10)\n", "\n", "# Now, we can use that variable.\n", "print('Your order total is', latte_total)" ] }, { "cell_type": "markdown", "id": "muslim-austria", "metadata": {}, "source": [ "\n", "* `total_amount` is returned to the main program.\n", "\n", "* The value in `total_amount` is saved as `latte_total`.\n", "\n", "* When we **return** something, it ends the function's execution and \"spits out\" whatever we are returning.\n", "\n", "---\n", "\n", "## We Do: Practicing Returns\n", "\n", "Let's fill this in together:\n", "\n", "- Define a function, `add_two`, that takes a parameter `number`.\n", "- It adds `2` to `number`, saving that in a new variable, `total`; print `total` out. Then, return `total`." ] }, { "cell_type": "code", "execution_count": null, "id": "twenty-christmas", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "unlimited-guard", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Discussion: Return Statements With Logic\n", "\n", "The `return` statement *exits a function*, not executing any further code in it. What do you think the following will print?\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "coordinated-calgary", "metadata": {}, "outputs": [], "source": [ "def mystery():\n", " return 6\n", " return 5\n", "\n", "my_number = mystery()\n", "print(my_number)" ] }, { "cell_type": "markdown", "id": "removable-creek", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Discussion: What Will Happen?\n", "\n", "What do you think will print out?\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "alleged-transport", "metadata": {}, "outputs": [], "source": [ "def add_bonus_points(score):\n", " if score > 50:\n", " return score + 10\n", " score += 20\n", " return score\n", "\n", "total_points = add_bonus_points(55)\n", "print(total_points)" ] }, { "cell_type": "markdown", "id": "bored-break", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Exiting a Function\n", "\n", "\n", "We can also use `return` by itself as a way to exit the function and prevent any code that follows from running.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "painful-wholesale", "metadata": {}, "outputs": [], "source": [ "def rock_and_roll(muted):\n", " song = \"It's only Rock 'N' Roll\"\n", " artist = \"Rolling Stones\"\n", "\n", " if (muted == True):\n", " return\n", " # Here, we use return as a way to exit a function\n", " # We don't actually return any value.\n", " print(\"Now playing: \", song, \" by \", artist)\n", "\n", "rock_and_roll(True)" ] }, { "cell_type": "markdown", "id": "instrumental-baking", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Quick Knowledge Check\n", "\n", "Looking at this code, where will the function stop if `x` is `10`?\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "educational-burton", "metadata": {}, "outputs": [], "source": [ "def categorize(x):\n", " if (x < 8):\n", " return 8\n", " x += 3\n", " if (x < 15):\n", " return x\n", " return 100\n", "\n" ] }, { "cell_type": "markdown", "id": "characteristic-simon", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Another Knowledge Check\n", "\n", "Take this simple `adder` function:\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "biological-evaluation", "metadata": {}, "outputs": [], "source": [ "def adder(number1, number2):\n", " return number1 + number2\n" ] }, { "cell_type": "markdown", "id": "acting-venue", "metadata": {}, "source": [ "\n", "Which of the following statements will result in an error?\n", "\n", "A. `adder(10, 100.)`
\n", "B. `adder(10, '10')`
\n", "C. `adder(100)`
\n", "D. `adder('abc', 'def')`
\n", "E. `adder(10, 20, 30)`
\n", "\n", "---\n", "\n", "## Quick Review: Return Statements\n", "\n", "Return statements allow us to get values back from functions:\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "still-introduction", "metadata": {}, "outputs": [], "source": [ "def add_two(number):\n", " total = number + 2\n", " print(total)\n", " return total\n", "\n", "final_var = add_two(3)\n", "print(final_var)" ] }, { "cell_type": "markdown", "id": "breeding-technology", "metadata": {}, "source": [ "\n", "Return statements also exit the function - no further code in the function happens!\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "quarterly-terrain", "metadata": {}, "outputs": [], "source": [ "def add_bonus_points(score):\n", " if score > 50:\n", " return score + 10\n", " score += 30\n", " return score\n", "\n", "total_points = add_bonus_points(55)\n", "print(total_points) # 65\n", "total_points = add_bonus_points(10)\n", "print(total_points) # 40" ] }, { "cell_type": "markdown", "id": "aerial-reasoning", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Temperature Conversion\n", "\n", "When we were learning about conditionals, we took a look at a program that let us know if it was too hot or too cold:\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "derived-armor", "metadata": {}, "outputs": [], "source": [ "temperature = 308\n", "if temperature > 299:\n", " print(\"It's too hot!\")\n", "elif temperature <= 299 and temperature > 288:\n", " print(\"It's just right!\")\n", "elif temperature <= 288 and temperature > 277:\n", " print(\"It's pretty cold!\")\n", "else:\n", " print(\"It's freezing!\")" ] }, { "cell_type": "markdown", "id": "micro-municipality", "metadata": {}, "source": [ "\n", "That's good logic, but Kelvins aren't incredibly useful on a day-to-day basis, unless you're a scientist. Let's use a function to convert temperatures.\n", "\n", "---\n", "\n", "## You Do: Temperature Conversion\n", "\n" ] }, { "cell_type": "markdown", "id": "textile-being", "metadata": {}, "source": [ "\n", "Here are the formulas to use:\n", "\n", "* **Celsius to Kelvin** : `K = °C + 273`\n", "* **Fahrenheit to Kelvin** : `K = (5/9) * (°F - 32) + 273`\n", "\n", "Try to use one function to convert from either Fahrenheit or Celsius based upon a second parameter." ] }, { "cell_type": "code", "execution_count": null, "id": "united-blair", "metadata": {}, "outputs": [], "source": [ "# create your function here\n", "\n", "\n", "# convert a temperature in either 'F' or 'C' into Kelvins using your function\n", "# store the result in a variable called 'temperature'\n", "# try out some different values and temperature scales\n", "\n", "\n", "if temperature > 299:\n", " print(\"It's too hot!\")\n", "elif temperature <= 299 and temperature > 288:\n", " print(\"It's just right!\")\n", "elif temperature <= 288 and temperature > 277:\n", " print(\"It's pretty cold!\")\n", "else:\n", " print(\"It's freezing!\")" ] }, { "cell_type": "markdown", "id": "nutritional-insight", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Exercise: Building a Copy\n", "\n", "Write a function, `copy_list`, that takes in a list, `original_list`, as a parameter. Your function should create a new list, `my_new_list` with the contents of the original list. Your function should return `my_new_list`." ] }, { "cell_type": "code", "execution_count": null, "id": "forced-cocktail", "metadata": {}, "outputs": [], "source": [ "# function defenition\n", "\n", "\n", "\n", "\n", "my_list = [1, 2, 3]\n", "my_new_list = copy_list(my_list)\n", "print(my_new_list)\n", "# Will print [1, 2, 3]" ] }, { "cell_type": "markdown", "id": "surgical-genesis", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Exercise: Reversing a List\n", "\n", "Write a function, `reverse_list`, that takes in a list, `my_list`, as a parameter. Your function should reverse the list and return it." ] }, { "cell_type": "code", "execution_count": null, "id": "needed-biodiversity", "metadata": {}, "outputs": [], "source": [ "# function defenition\n", "\n", "\n", "\n", "my_list = [1, 2, 3]\n", "reversed_list = reverse_list(my_list)\n", "print(reversed_list)\n", "# Will print [3, 2, 1]" ] }, { "cell_type": "markdown", "id": "yellow-handbook", "metadata": {}, "source": [ "\n", "---\n", "\n", "## Summary + Q&A:\n", "\n", "Can you now:\n", "\n", "- Identify when to use a function?\n", "- Create and call a function with arguments?\n", "- Return a value from a function?" ] } ], "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.7.6" } }, "nbformat": 4, "nbformat_minor": 5 }