{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions\n", "\n", "## Introduction to Functions\n", "\n", "This lecture will consist of explaining what a function is in Python and how to create one. Functions will be one of our main building blocks when we construct larger and larger amounts of code to solve problems.\n", "\n", "### What is a function?\n", "\n", "Formally, a function is a useful device that groups together a set of statements so they can be run more than once. They can also let us specify parameters that can serve as inputs to the functions.\n", "\n", "On a more fundamental level, functions allow us to not have to repeatedly write the same code again and again. If you remember back to the lessons on strings and lists, remember that we used a function len() to get the length of a string. Since checking the length of a sequence is a common task you would want to write a function that can do this repeatedly at command.\n", "\n", "Functions will be one of most basic levels of reusing code in Python, and it will also allow us to start thinking of program design (we will dive much deeper into the ideas of design when we learn about Object Oriented Programming)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Why even use functions?\n", "\n", "Put simply, you should use functions when you plan on using a block of code multiple times. The function will allow you to call the same block of code without having to write it multiple times. This in turn will allow you to create more complex Python scripts. To really understand this though, we should actually write our own functions! " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Function Topics\n", "* def keyword\n", "* simple example of a function\n", "* calling a function with ()\n", "* accepting parameters\n", "* print versus return\n", "* adding in logic inside a function\n", "* multiple returns inside a function\n", "* adding in loops inside a function\n", "* tuple unpacking\n", "* interactions between functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### def keyword\n", "\n", "Let's see how to build out a function's syntax in Python. It has the following form:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def name_of_function(arg1,arg2):\n", " '''\n", " This is where the function's Document String (docstring) goes.\n", " When you call help() on your function it will be printed out.\n", " '''\n", " # Do stuff here\n", " # Return desired result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We begin with def then a space followed by the name of the function. Try to keep names relevant, for example len() is a good name for a length() function. Also be careful with names, you wouldn't want to call a function the same name as a [built-in function in Python](https://docs.python.org/3/library/functions.html) (such as len).\n", "\n", "Next come a pair of parentheses with a number of arguments separated by a comma. These arguments are the inputs for your function. You'll be able to use these inputs in your function and reference them. After this you put a colon.\n", "\n", "Now here is the important step, you must indent to begin the code inside your function correctly. Python makes use of *whitespace* to organize code. Lots of other programing languages do not do this, so keep that in mind.\n", "\n", "Next you'll see the docstring, this is where you write a basic description of the function. Using Jupyter and Jupyter Notebooks, you'll be able to read these docstrings by pressing Shift+Tab after a function name. Docstrings are not necessary for simple functions, but it's good practice to put them in so you or other people can easily understand the code you write.\n", "\n", "After all this you begin writing the code you wish to execute.\n", "\n", "The best way to learn functions is by going through examples. So let's try to go through examples that relate back to the various objects and data structures we learned about before." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Simple example of a function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def say_hello():\n", " print('hello')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Calling a function with ()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Call the function:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "say_hello()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you forget the parenthesis (), it will simply display the fact that say_hello is a function. Later on we will learn we can actually pass in functions into other functions! But for now, simply remember to call functions with ()." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "say_hello" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Accepting parameters (arguments)\n", "Let's write a function that greets people with their name." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def greeting(name):\n", " print(f'Hello {name}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "greeting('Jose')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using return\n", "So far we've only seen print() used, but if we actually want to save the resulting variable we need to use the **return** keyword.\n", "\n", "Let's see some example that use a return statement. return allows a function to *return* a result that can then be stored as a variable, or used in whatever manner a user wants.\n", "\n", "### Example: Addition function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def add_num(num1,num2):\n", " return num1+num2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "add_num(4,5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Can also save as variable due to return\n", "result = add_num(4,5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What happens if we input two strings?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "add_num('one','two')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Very Common Question: \"What is the difference between *return* and *print*?\"\n", "\n", "**The return keyword allows you to actually save the result of the output of a function as a variable. The print() function simply displays the output to you, but doesn't save it for future use. Let's explore this in more detail**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def print_result(a,b):\n", " print(a+b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def return_result(a,b):\n", " return a+b" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print_result(10,5)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# You won't see any output if you run this in a .py script\n", "return_result(10,5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**But what happens if we actually want to save this result for later use?**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_result = print_result(20,20)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_result" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(my_result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Be careful! Notice how print_result() doesn't let you actually save the result to a variable! It only prints it out, with print() returning None for the assignment!**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_result = return_result(20,20)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_result" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_result + my_result" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Adding Logic to Internal Function Operations\n", "\n", "So far we know quite a bit about constructing logical statements with Python, such as if/else/elif statements, for and while loops, checking if an item is **in** a list or **not in** a list (Useful Operators Lecture). Let's now see how we can perform these operations within a function." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Check if a number is even " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Recall the mod operator % which returns the remainder after division, if a number is even then mod 2 (% 2) should be == to zero.**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "2 % 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "20 % 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "21 % 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "20 % 2 == 0" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "21 % 2 == 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Let's use this to construct a function. Notice how we simply return the boolean check.**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def even_check(number):\n", " return number % 2 == 0" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "even_check(20)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "even_check(21)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Check if any number in a list is even\n", "\n", "Let's return a boolean indicating if **any** number in a list is even. Notice here how **return** breaks out of the loop and exits the function" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def check_even_list(num_list):\n", " # Go through each number\n", " for number in num_list:\n", " # Once we get a \"hit\" on an even number, we return True\n", " if number % 2 == 0:\n", " return True\n", " # Otherwise we don't do anything\n", " else:\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Is this enough? NO! We're not returning anything if they are all odds!**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "check_even_list([1,2,3])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "check_even_list([1,1,1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** VERY COMMON MISTAKE!! LET'S SEE A COMMON LOGIC ERROR, NOTE THIS IS WRONG!!!**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def check_even_list(num_list):\n", " # Go through each number\n", " for number in num_list:\n", " # Once we get a \"hit\" on an even number, we return True\n", " if number % 2 == 0:\n", " return True\n", " # This is WRONG! This returns False at the very first odd number!\n", " # It doesn't end up checking the other numbers in the list!\n", " else:\n", " return False" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UH OH! It is returning False after hitting the first 1\n", "check_even_list([1,2,3])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Correct Approach: We need to initiate a return False AFTER running through the entire loop**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def check_even_list(num_list):\n", " # Go through each number\n", " for number in num_list:\n", " # Once we get a \"hit\" on an even number, we return True\n", " if number % 2 == 0:\n", " return True\n", " # Don't do anything if its not even\n", " else:\n", " pass\n", " # Notice the indentation! This ensures we run through the entire for loop \n", " return False" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "check_even_list([1,2,3])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "check_even_list([1,3,5])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Return all even numbers in a list\n", "\n", "Let's add more complexity, we now will return all the even numbers in a list, otherwise return an empty list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def check_even_list(num_list):\n", " \n", " even_numbers = []\n", " \n", " # Go through each number\n", " for number in num_list:\n", " # Once we get a \"hit\" on an even number, we append the even number\n", " if number % 2 == 0:\n", " even_numbers.append(number)\n", " # Don't do anything if its not even\n", " else:\n", " pass\n", " # Notice the indentation! This ensures we run through the entire for loop \n", " return even_numbers" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "check_even_list([1,2,3,4,5,6])" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "check_even_list([1,3,5])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Returning Tuples for Unpacking" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "** Recall we can loop through a list of tuples and \"unpack\" the values within them**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "stock_prices = [('AAPL',200),('GOOG',300),('MSFT',400)]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for item in stock_prices:\n", " print(item)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for stock,price in stock_prices:\n", " print(stock)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for stock,price in stock_prices:\n", " print(price)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Similarly, functions often return tuples, to easily return multiple results for later use.**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's imagine the following list:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "work_hours = [('Abby',100),('Billy',400),('Cassie',800)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The employee of the month function will return both the name and number of hours worked for the top performer (judged by number of hours worked)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def employee_check(work_hours):\n", " \n", " # Set some max value to intially beat, like zero hours\n", " current_max = 0\n", " # Set some empty value before the loop\n", " employee_of_month = ''\n", " \n", " for employee,hours in work_hours:\n", " if hours > current_max:\n", " current_max = hours\n", " employee_of_month = employee\n", " else:\n", " pass\n", " \n", " # Notice the indentation here\n", " return (employee_of_month,current_max)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "employee_check(work_hours)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Interactions between functions\n", "\n", "Functions often use results from other functions, let's see a simple example through a guessing game. There will be 3 positions in the list, one of which is an 'O', a function will shuffle the list, another will take a player's guess, and finally another will check to see if it is correct. This is based on the classic carnival game of guessing which cup a red ball is under." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**How to shuffle a list in Python**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "example = [1,2,3,4,5]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from random import shuffle" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Note shuffle is in-place\n", "shuffle(example)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "example" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**OK, let's create our simple game**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mylist = [' ','O',' ']" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def shuffle_list(mylist):\n", " # Take in list, and returned shuffle versioned\n", " shuffle(mylist)\n", " \n", " return mylist" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mylist " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "shuffle_list(mylist)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def player_guess():\n", " \n", " guess = ''\n", " \n", " while guess not in ['0','1','2']:\n", " \n", " # Recall input() returns a string\n", " guess = input(\"Pick a number: 0, 1, or 2: \")\n", " \n", " return int(guess) " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "player_guess()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we will check the user's guess. Notice we only print here, since we have no need to save a user's guess or the shuffled list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def check_guess(mylist,guess):\n", " if mylist[guess] == 'O':\n", " print('Correct Guess!')\n", " else:\n", " print('Wrong! Better luck next time')\n", " print(mylist)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we create a little setup logic to run all the functions. Notice how they interact with each other!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Initial List\n", "mylist = [' ','O',' ']\n", "\n", "# Shuffle It\n", "mixedup_list = shuffle_list(mylist)\n", "\n", "# Get User's Guess\n", "guess = player_guess()\n", "\n", "# Check User's Guess\n", "#------------------------\n", "# Notice how this function takes in the input \n", "# based on the output of other functions!\n", "check_guess(mixedup_list,guess)" ] } ], "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" }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 4 }