{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Methods\n", "\n", "- string, list, & dictionary\n", "- in place vs not in place\n", "- relationship to functions" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Clicker Question #1\n", "\n", "What will the following code snippet print?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def my_func(my_dictionary):\n", " \n", " output = []\n", "\n", " for item in my_dictionary:\n", " value = my_dictionary[item]\n", " output.append(value) #append method adds an item to end of a list\n", " \n", " return output\n", "\n", "# create dictionary and execute function\n", "dictionary = {'first' : 1, 'second' : 2, 'third' : 3}\n", "out = my_func(dictionary)\n", "\n", "print(out)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- A) ['first', 'second', 'third'] \n", "- B) {1, 2, 3}\n", "- C) ['first', 1, 'second', 2, 'third', 3] \n", "- D) [1, 2, 3] \n", "- E) None" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true, "jupyter": { "outputs_hidden": true }, "slideshow": { "slide_type": "slide" } }, "source": [ "## Methods" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "<div class=\"alert alert-success\">\n", "<b>Methods</b> are functions that are defined and called directly on an object. \n", "</div>\n", "\n", "<div class=\"alert alert-success\">\n", "For our purposes, <b>objects</b> are any data variable. \n", "</div>" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Method Examples\n", "\n", "A method is a function applied directly to the object you call it on." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "General form of a method:\n", "\n", "```python\n", "object.method()\n", "```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "In other words: methods \"belong to\" an object." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# The `append` method, defined on lists\n", "my_list = [1, 2, 3]\n", "my_list.append(4)\n", "print(my_list)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "The method `append()` is called directly on the list `my_list`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# append is a method for lists\n", "# this will error with a string\n", "my_string = 'cogs18'\n", "my_string.append('!')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# The `is_integer()` method, defined on floats\n", "my_float = 12.2\n", "my_float.is_integer()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# The `is_integer()` method, attempted on an integer\n", "# this code will produce an error\n", "my_int = 12\n", "my_int.is_integer()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## String Methods\n", "\n", "There are a whole bunch of string methods, all described [here](https://www.w3schools.com/python/python_ref_string.asp). We'll review a few of the most commonly used here." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Make a string all lower case\n", "'aBc'.lower()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Make a string all upper case\n", "'aBc'.upper()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Capitalize a string\n", "'python is great'.capitalize()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Find the index of where a string starts \n", "'Hello, my name is'.find('name')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Clicker Question #2\n", "\n", "What will the following code snippet print out?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "inputs = ['fIx', 'tYpiNg', 'lIkE', 'tHiS']\n", "output = ''\n", "\n", "for element in inputs:\n", " output = output + element.lower() + ' '\n", "\n", "output.capitalize()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- A) 'fix typing like this ' \n", "- B) ['fix', 'typing', 'like', 'this'] \n", "- C) 'Fix typing like this ' \n", "- D) 'Fix typing like this' \n", "- E) 'Fixtypinglikethis'" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## List Methods\n", "\n", "There are also a bunch of list methods, all described [here](https://www.w3schools.com/python/python_ref_list.asp). You've seen some of these before, but we'll review a few of the most commonly used here." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# sort sorts integers in numerical orders\n", "ints = [16, 88, 33, 40]\n", "ints.sort()\n", "ints" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "ints.sort(reverse=True)\n", "ints" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# append adds to the end of a list\n", "ints.append(2)\n", "ints" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# remove value from list\n", "ints.remove(40)\n", "ints" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list.remove?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# reverse order of list\n", "ints.reverse()\n", "ints" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Clicker Question #3\n", "\n", "What will the following code snippet print out?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "list_string = ['a', 'c', 'd', 'b']\n", "list_string.sort()\n", "list_string.reverse()\n", "list_string" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- A) ['a', 'c', 'd', 'b']\n", "- B) ['a', 'b', 'c', 'd']\n", "- C) ['d', 'c', 'b', 'a'] \n", "- D) ['d', 'b', 'a', 'c'] \n", "- E) ['d', 'a', 'b', 'c']" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Dictionary Methods\n", "\n", "As with string and list methods, there are many described [here](https://www.w3schools.com/python/python_ref_dictionary.asp) that are helpful when working with dictionaries.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "car = {\n", " \"brand\": \"BMW\",\n", " \"model\": \"M5\",\n", " \"year\": 2019\n", "}\n", "\n", "# keys() returns the keys of a dictionary\n", "car.keys()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# get returns the value of a specified key\n", "mod = car.get('model')\n", "\n", "# equivalent\n", "mod2 = car['model']\n", "\n", "print(mod)\n", "print(mod2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "# previously done this by indexing\n", "print(car['model'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# update adds a key-value pair\n", "car.update({\"color\": \"Black\"})\n", "\n", "print(car) " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Clicker Question #4\n", "\n", "Assuming `dictionary` is a dictionary that exists, what would the following accomplish:\n", "\n", "```python\n", "\n", "dictionary.get('letter')\n", "\n", "```\n", "\n", "- A) Return the key for the value 'letter' from `dictionary`\n", "- B) Add the key 'letter' to `dictionary`\n", "- C) Add the value 'letter' to `dictionary`\n", "- D) Return the value for the key 'letter' from `dictionary`\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Clicker Question #5\n", "\n", "Which method would you use to add a new key-value pair to a dictionary?\n", "\n", "- A) `.append()`\n", "- B) `.get()`\n", "- C) `.keys()` \n", "- D) `.update()`\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Methods: In Place vs Not In Place" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "<div class=\"alert alert-success\">\n", "Some methods update the object directly (in place), whereas others return an updated version of the input. \n", "</div>" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### List methods that are in place" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Reverse a list\n", "my_list = ['a', 'b', 'c']\n", "my_list.reverse()\n", "\n", "print(my_list)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Sort a list\n", "my_numbers = [13, 3, -1]\n", "my_numbers.sort()\n", "\n", "print(my_numbers)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Dictionary methods that are not in place" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "car" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Return the keys in the dictionary\n", "out = car.keys() " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# print keys\n", "print(type(out))\n", "print(out)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# car has not changed\n", "print(type(car))\n", "print(car)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Return the values in the dicionary\n", "car.values()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Finding Methods" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Typing the object/variable name you want to find methods for followed by a '.' and then pressing tab will display all the methods available for that type of object." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Define a test string\n", "my_string = 'Python'" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# See all the available methods on an object with tab complete\n", "my_string." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Using the function `dir()` returns all methods available" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# For our purposes now, you can ignore any leading underscores (these are special methods)\n", "dir(my_string)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Correspondance Between Functions & Methods" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "All methods are functions. Methods are special functions *attached* to a variable type. All functions are NOT methods. \n", "\n", "Note that:\n", "\n", "```python\n", "my_variable.function_call()\n", "```\n", "\n", "acts like:\n", "\n", "```python\n", "function_call(my_variable)\n", "```\n", "\n", "A function that we can call directly on a variable (a method) acts like a shortcut for passing that variable into a function. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "notes" } }, "source": [ "### Functions: Reminders\n", "\n", "Additional notes included here to remind you of points we've already discussed. Not presented in class, but feel free to review and gain additional clarificaiton.\n", "\n", "1. `def` defines a function\n", "2. `function_name()` - parentheses are required to execute a function\n", "3. `function_name(input1)` - input parameters are specified within the function parentheses \n", "4. `function_name(input1, input2)` - functions can take multiple parameters as inputs\n", " - `input1` and `input2` can then be used within your function when it executes\n", "5. To store the output from a function, you'll need a `return` statement" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "notes" } }, "source": [ "#### For example....\n", "\n", "If you write a function called `is_odd()` which takes an input `value`, " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "def is_odd(value):\n", " if value % 2 != 0:\n", " answer = True\n", " else:\n", " answer = False\n", " \n", " return answer" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "notes" } }, "source": [ "to use that function, you would execute `is_odd(value)` ....something like `is_odd(value = 6)`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "out = is_odd(6)\n", "out" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "notes" } }, "source": [ "Later on, if you wanted to use that function _within another function_ you still have to pass an input to the function." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "def new_function(my_list):\n", " output = []\n", " for val in my_list:\n", " if is_odd(val):\n", " output.append('yay!')\n", " return output\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true, "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "new_function([1,2,3,4])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## More Functions & Methods\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "### `sort_array`\n", "\n", "A version of a **selection sort**:\n", "- loop through current list\n", "- find lowest item\n", "- put that at the front of your sorted list\n", "- remove lowest item from current list\n", "- wash, rinse, repeat" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def sort_array(array_to_sort):\n", " \"\"\"A function to sort an array.\"\"\"\n", "\n", " is_sorted = False # Keeps track of when we are done sorting\n", " sorted_array = [] # A new list that we will use to \n", " \n", " while not is_sorted:\n", "\n", " lowest = None\n", " for item in array_to_sort:\n", " if lowest == None: # If not defined (first element) set the current element as lowest\n", " lowest = item\n", " if item < lowest:\n", " lowest = items\n", " \n", " # these next two lines uses some new (to us) list methods\n", " sorted_array.append(lowest) # Add the lowest value to our sorted array output\n", " array_to_sort.remove(lowest) # Drop the now sorted value from the original array\n", "\n", " if len(array_to_sort) == 0: # When `array_to_sort` is empty, we are done sorting\n", " is_sorted = True\n", " \n", " return sorted_array" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Using `sort_array`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Sort an array of integers\n", "unsorted_array = [12, 7, 19, 12, 25]\n", "sorted_array = sort_array(unsorted_array)\n", "print(sorted_array)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Sort an array of floats\n", "unsorted_array = [21.3, 56.7, 2.3, 2.9, 99.9]\n", "sorted_array = sort_array(unsorted_array)\n", "print(sorted_array)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## SideNote: `sorted`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Sort a list, with `sorted`\n", "data = [7, 4, 6]\n", "sorted(data)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# what about a list of strings?\n", "sorted(['asdf','abcd'])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Sort different data types\n", "print(sorted(['a', 'c', 'b']))\n", "print(sorted([True, False, True]))\n", "print(sorted([[1, 4], [1, 2]]))" ] } ], "metadata": { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.11.8" }, "rise": { "scroll": true } }, "nbformat": 4, "nbformat_minor": 4 }