{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Introduction to Conditionals and further basics\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "This is an rough introduction to some basic material. There are many good sources for this out there. I relied in part on old notes from [this course](https://cogs18.github.io/intro), which seems to run in parallel to ours." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Conditionals\n", "\n", "- `if`\n", "- `elif`\n", "- `else`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Conditionals: if" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "Conditionals are statements that check for a condition, using the `if` statement, and then only execute a set of code if the condition evaluates as `True`.\n", "
" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "condition = False\n", "\n", "if condition:\n", " print('This code executes if the condition evaluates as True.')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Conditional: else" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "After an `if`, you can use an `else` that will run if the conditional(s) above have not run.\n", "
" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This code executes if the condition evaluates as True.\n" ] } ], "source": [ "condition = True\n", "\n", "if condition:\n", " print('This code executes if the condition evaluates as True.')\n", "else: \n", " print('This code executes if the condition evaluates as False')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Conditional: elif" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "After an if statement, you can have any number of `elif`'s (meaning 'else if') to check other conditions.\n", "
" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "scrolled": true, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This code executes if both condition_1 and condition_2 evaluate as False\n" ] } ], "source": [ "condition_1 = False\n", "condition_2 = False\n", "\n", "if condition_1:\n", " print('This code executes if condition_1 evaluates as True.')\n", "elif condition_2:\n", " print('This code executes if condition_1 did not evaluate as True, but condition_2 does.')\n", "else: \n", " print('This code executes if both condition_1 and condition_2 evaluate as False')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### `elif` without an `else`\n", "\n", "An else statement is not required, but if both the `if` and the `elif` condtions are not met (both evaluate as `False`), then nothing is returned." ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "condition_1 = False\n", "condition_2 = False\n", "\n", "if condition_1:\n", " print('This code executes if condition_1 evaluates as True.')\n", "elif condition_2:\n", " print('This code executes if condition_1 did not evaluate as True, but condition_2 does.')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### `elif` *after* an `else` does not make sense\n", "\n", "The order will alwas be `if`-`elif`-`else`...with only the `if` being required. If the `elif` is at the end...it will never be tested, as the `else` will have already returned a value once reached (and thus Python will throw an erro)." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 9)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m9\u001b[0m\n\u001b[0;31m elif condition_2:\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "## THIS CODE WILL PRODUCE AN ERROR\n", "condition_1 = False\n", "condition_2 = False\n", "\n", "if condition_1:\n", " print('This code executes if condition_1 evaluates as True.')\n", "else: \n", " print('This code executes if both condition_1 and condition_2 evaluate as False')\n", "elif condition_2:\n", " print('This code executes if condition_1 did not evaluate as True, but condition_2 does.')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Conditionals With Value Comparisons" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "Any expression that can be evaluated as a boolean, such as value comparisons, can be used with conditionals.\n", "
" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Oh no.\n" ] } ], "source": [ "language = \"Python\"\n", "language = \"R\"\n", "\n", "if language == \"Python\":\n", " print(\"Yay!\")\n", "elif language == \"R\":\n", " print(\"Oh no.\")\n", "else:\n", " print(\"Get yourself a programming language!\")" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before Conditional\n", " elif statement execution\n", "After Conditional\n" ] } ], "source": [ "# Exploring conditionals\n", "number = 6\n", "\n", "print('Before Conditional')\n", " \n", "if number < 5:\n", " print(' if statement execution')\n", "elif number > 5:\n", " print(' elif statement execution')\n", "\n", "print('After Conditional')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Properties of conditionals\n", "\n", "- All conditionals start with an `if`, can have an optional and variable number of `elif`'s and an optional `else` statement\n", "- Conditionals can take any expression that can be evaluated as `True` or `False`. \n", "- At most one component (`if` / `elif` / `else`) of a conditional will run\n", "- The order of conditional blocks is always `if` then `elif`(s) then `else`\n", "- Code is only ever executed if the condition is met" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Control Flow - Loops\n", "\n", "- `while`\n", "- `for`\n", " - `range`\n", " - `continue`\n", " - `break`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Loops" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "A loop is a procedure to repeat a piece of code.\n", "
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Avoid copy + pasting\n", "\n", "For repetitive actions, if you find yourself copying + pasting, rethink your strategy.\n", "\n", "Loops are one way to avoid this." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "lst = ['you@yahoo.com', 'them@bing.com']\n", "\n", "email = lst[0]\n", "\n", "email = lst[1]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## While Loops" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "A while loop is a procedure to repeat a piece of code while some condition is still met. \n", "
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## While Loops" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-5\n", "-4\n", "-3\n", "-2\n", "-1\n" ] } ], "source": [ "number = -5\n", "\n", "while number < 0:\n", " print(number)\n", " number = number + 1" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "14\n" ] } ], "source": [ "keep_looping = True\n", "counter = 0\n", "\n", "while keep_looping:\n", "\n", " counter = counter + 1\n", " \n", " if counter > 13:\n", " keep_looping = False\n", "\n", "print(counter)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## For Loops" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "A for loop is a procedure to repeat code for every element in a sequence.\n", "
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### For Loop Example I\n", "\n", "Looping through a list" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A\n", "True\n", "12\n", "\tLast value: 12\n" ] } ], "source": [ "# Define a list of items\n", "list_of_items = ['A', True, 12]\n", "\n", "# Loop across each element\n", "for my_item in list_of_items:\n", " print(my_item)\n", " \n", "print('\\tLast value: ', my_item)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### For Loop Example II\n", "\n", "Looping through a string" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p\n", "y\n", "t\n", "h\n", "o\n", "n\n", " \n", "i\n", "s\n", " \n", "a\n", "w\n", "e\n", "s\n", "o\n", "m\n", "e\n" ] } ], "source": [ "# Loop across items in a string\n", "for char in 'python is awesome': \n", " print(char)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Chemnitz!\n", "Hello Chemnitz!\n", "Hello Chemnitz!\n", "Hello Chemnitz!\n", "Hello Chemnitz!\n", "Hello Chemnitz!\n" ] } ], "source": [ "# Loop across items in a string\n", "for _ in 'python': \n", " print(\"Hello Chemnitz!\")\n", " # this code does some printing" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## `range`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "`range` is an operator to create a range of numbers, that is often used with loops.\n", "
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### `range` Examples" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for ind in [0,1,2,3,4]:\n", " print(ind)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1 2 3 4 5 6 7 8 9\n" ] } ], "source": [ "# the asterisk here unpacks the range\n", "# don't worry about this syntax now\n", "print(*range(0,10))" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "# Loop across a sequence of numbers, using range\n", "for ind in range(0, 10):\n", " print(ind)" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "4\n" ] } ], "source": [ "# Range, like indexing, is defined by 'start', 'stop', 'step'\n", "for ind in range(2, 6, 2):\n", " print(ind)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "scrolled": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "40\n", "41\n", "42\n", "43\n", "44\n", "45\n", "46\n", "47\n", "48\n", "49\n", "50\n", "51\n", "The tea is too hot!\n", "52\n", "The tea is too hot!\n", "53\n", "The tea is too hot!\n", "54\n", "The tea is too hot!\n", "55\n", "The tea is too hot!\n", "56\n", "The tea is too hot!\n", "57\n", "The tea is too hot!\n", "58\n", "The tea is too hot!\n", "59\n", "The tea is too hot!\n", "60\n", "The tea is too hot!\n", "61\n", "The tea is too hot!\n", "62\n", "The tea is too hot!\n", "63\n", "The tea is too hot!\n", "64\n", "The tea is too hot!\n", "65\n", "The tea is too hot!\n", "66\n", "The tea is too hot!\n", "67\n", "The tea is too hot!\n", "68\n", "The tea is too hot!\n", "69\n", "The tea is too hot!\n" ] } ], "source": [ "# using range in example above\n", "for temp in range(40, 70): \n", " print(temp)\n", " if(temp > 50):\n", " print('The tea is too hot!')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## `continue`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "`continue` is a special operator to jump ahead to the next iteration of a loop.\n", "
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### `continue` examples" ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "3\n" ] } ], "source": [ "lst = [0, 1, 2, 3]\n", "\n", "for item in lst:\n", "\n", " if item == 2:\n", " continue \n", " print(item)" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cogs9\n", "cogs9!\n", "cogs108\n", "cogs108!\n" ] } ], "source": [ "courses = ['cogs9', 'cogs18', 'cogs108']\n", "\n", "for course in courses:\n", "\n", " if course == 'cogs18':\n", " continue\n", " \n", " print(course)\n", " print(course + '!')" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "t\n", "h\n", "o\n", "n\n" ] } ], "source": [ "string = \"python\"\n", "\n", "for char in string: \n", " \n", " if char == \"p\" or char == \"y\":\n", " continue\n", " \n", " print(char)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## `break`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "`break` is a special operator to break out of a loop.\n", "
" ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Establishing Connection...\n" ] } ], "source": [ "connected = False\n", "\n", "while not connected:\n", " \n", " # Try and establish connection (placeholder code)\n", " print('Establishing Connection...')\n", " \n", " break" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### `break` examples" ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "Hello sunshine\n", "1\n", "Hello sunshine\n" ] } ], "source": [ "lst = [0, 1, 2, 3]\n", "\n", "for item in lst:\n", " \n", " if item == 2:\n", " break\n", " \n", " print(item)\n", " \n", " print(\"Hello sunshine\")" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cogs9\n" ] } ], "source": [ "courses = [\"cogs9\", \"cogs18\", \"cogs108\"]\n", "\n", "for course in courses:\n", "\n", " if course == \"cogs18\":\n", " break\n", " \n", " print(course)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "l\n", "o\n", "v\n", "e\n", " \n" ] } ], "source": [ "string = \"love python\"\n", "\n", "for char in string: \n", " if char == \"p\" or char == \"y\":\n", " break\n", " \n", " print(char)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "114\n", "115\n", "116\n", "The tea is too hot!\n" ] } ], "source": [ "# using range in example above\n", "for temp in range(114, 119): \n", " print(temp)\n", " \n", " if(temp > 115):\n", " print('The tea is too hot!')\n", " break" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Functions I\n", "\n", "- defining a function\n", " - `def`\n", " - `return`\n", "- executing a function\n", " - parameters\n", " - separate namespace" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Functions\n", "\n", "
\n", "A function is a re-usable piece of code that performs operations on a specified set of variables, and returns the result.\n", "
" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# you've seen functions before\n", "my_var = [3, 4, 5]\n", "type(my_var)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Copy + Pasting the same/similar bit of code is to be avoided.\n", "\n", "**Loops** were one way to avoid this.\n", "\n", "**Functions** are a another!" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Modular Programming\n", "\n", "
\n", "Modular programming is an approach to programming that focuses on building programs from indendent modules ('pieces'). \n", "
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Functions for Modular Programming" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- Functions allow us to flexibly re-use pieces of code\n", "- Each function is independent of every other function, and other pieces of code\n", "- Functions are the building blocks of programs, and can be flexibly combined and executed in specified orders\n", " - This allows us to build up arbitrarily complex, well-organized programs" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "list" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# you've seen functions before\n", "# here we use the type() function\n", "my_var = [3, 4, 5]\n", "type(my_var)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# the function len() doesn't depend on type()\n", "# but they can both be used on the same variable\n", "len(my_var)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Function Example I\n", "\n", "When you use `def` you are creating a **user-defined function**." ] }, { "cell_type": "code", "execution_count": 64, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# define a function: print_value\n", "# num is a parameter for the function\n", "def print_value(num):\n", " \n", " # do some operation\n", " print(num)" ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "# excecute a function by calling function by name\n", "# adding input within parentheses\n", "print_value(num = 8)" ] }, { "cell_type": "code", "execution_count": 67, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "# equivalent function call\n", "# without specifying parameter\n", "print_value(8)" ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "scrolled": true, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n", "None\n" ] } ], "source": [ "## why is it printing None?\n", "## lets look at return below\n", "new_var = print_value(6)\n", "print(new_var)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "All this function is doing is printing the input. It's not actually *storing* any new information. To do that, we need to use `return`." ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "# improving that function using return\n", "def return_value(num):\n", " \n", " # do some operation\n", " output = num\n", " \n", " # return an asnwer\n", " return output" ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# excecute that function\n", "return_value(6)" ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "# execute function but assign output \n", "# store that output in variable new_val\n", "new_val = return_value(8)\n", "print(new_val)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Function Example II\n", "\n", "Something more interesting than just printing or storing a single value" ] }, { "cell_type": "code", "execution_count": 72, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def add_two_numbers(num1, num2):\n", " \n", " # Do some operations on the input variables\n", " answer = num1 + num2\n", " \n", " # Return the answer\n", " return answer" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "scrolled": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n" ] } ], "source": [ "# Execute our function again, on some other inputs\n", "output = add_two_numbers(1, 4)\n", "print(output)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Function Example III\n", "\n", "We aren't limited to a single operation within a function. We can use multiple operations and all of the concepts we've used previously (`if`, `elif`, `else` and conditionals)." ] }, { "cell_type": "code", "execution_count": 75, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# determine if a value is even or odd\n", "def evenOdd(value): \n", " if (value % 2 == 0): \n", " print(\"even\")\n", " else: \n", " print(\"odd\")\n", " \n" ] }, { "cell_type": "code", "execution_count": 78, "metadata": { "scrolled": true, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "even\n" ] } ], "source": [ "# Execute our function\n", "# note that it's only printing the output\n", "evenOdd(202002)" ] }, { "cell_type": "code", "execution_count": 80, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "# determine if a value is even or odd\n", "# and return that value\n", "def evenOdd(value): \n", " if (value % 2 == 0): \n", " out = \"even\"\n", " else: \n", " out = \"odd\"\n", " \n", " return out" ] }, { "cell_type": "code", "execution_count": 82, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "even\n" ] } ], "source": [ "# Execute our function\n", "# note that it's only printing the output\n", "my_val = evenOdd(-12)\n", "print(my_val)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "With functions, the logic behind our code no longer requires it to be executed from top to bottom.\n", "\n", "The cost of potential confusion is *definitely* offset by the benefits of writing functions and using modular code." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Function Properties" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- Functions are defined using `def` followed by `:`, which opens a code-block that comprises the function\n", " - Running code with a `def` block *defines* the function (but does not *execute* it)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- Functions are *executed* using parentheses - '()'\n", " - This is when the code inside a function is actually run" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- Functions have their own namespace\n", " - They only have access to variables explicitly passed into them" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- Inside a function, there is code that performs operations on the available variables" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- Functions use the special operator `return` to exit the function, passing out any specified variables" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "- When you use a function, you can assign the output to a variable" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Function Namespace I" ] }, { "cell_type": "code", "execution_count": 83, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Variable Type Data/Info\n", "---------------------------------------\n", "add_two_numbers function \n", "char str n\n", "condition bool True\n", "condition_1 bool False\n", "condition_2 bool False\n", "connected bool False\n", "counter int 14\n", "course str cogs108\n", "courses list n=3\n", "evenOdd function \n", "hans str n\n", "ind int 4\n", "item int 2\n", "keep_looping bool False\n", "language str R\n", "list_of_items list n=3\n", "lst list n=4\n", "my_item int 12\n", "my_val str even\n", "my_var list n=3\n", "new_val int 8\n", "new_var NoneType None\n", "number int 0\n", "output int 5\n", "print_value function \n", "return_value function \n", "temp int 69\n" ] } ], "source": [ "# We can check defined variables with `%whos`\n", "%whos" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Function Namespaces II" ] }, { "cell_type": "code", "execution_count": 84, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def check_function_namespace(function_input):\n", " # Check what is defined and available inside the function\n", " # a=2\n", " print(locals())" ] }, { "cell_type": "code", "execution_count": 88, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'function_input': 2}\n" ] } ], "source": [ "# Functions don't `see` everything\n", "check_function_namespace(2)" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'function_input': True}\n" ] } ], "source": [ "# Functions don't `see` everything\n", "check_function_namespace(True)" ] }, { "cell_type": "code", "execution_count": 89, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# using two different inputs to a function\n", "def check_function_namespace2(function_input, other_name):\n", " # Check what is defined and available inside the function\n", " print(locals())" ] }, { "cell_type": "code", "execution_count": 90, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'other_name': True, 'function_input': 1}\n" ] } ], "source": [ "# returning what each input is storing\n", "check_function_namespace2(1, True)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Function Namespaces III\n", "\n", "Names defined inside a function only exist within the function." ] }, { "cell_type": "code", "execution_count": 91, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'function_input': 'I am a variable'}\n", "I am a variable\n" ] } ], "source": [ "# Names used inside a function are independent of those used outside\n", "# variables defined outside of functions are global variables\n", "# global variables are always available\n", "my_var = 'I am a variable'\n", "\n", "check_function_namespace(my_var)\n", "\n", "print(my_var)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Function - Execution Order" ] }, { "cell_type": "code", "execution_count": 93, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def change_var(my_var):\n", " my_var = 'I am something else'\n", " print('Inside function: \\t\\t', my_var)" ] }, { "cell_type": "code", "execution_count": 94, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'I am a variable'" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# my_var in the global namespace\n", "my_var" ] }, { "cell_type": "code", "execution_count": 95, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Inside function: \t\t I am something else\n" ] } ], "source": [ "# my_var within the function\n", "change_var(my_var)" ] }, { "cell_type": "code", "execution_count": 97, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'I am a variable'" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# my_var in the global namespace remains unchanged\n", "my_var" ] }, { "cell_type": "code", "execution_count": 98, "metadata": { "scrolled": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Outside, before function: \t I am a variable\n", "Inside function: \t\t I am something else\n", "Outside, after function: \t I am a variable\n" ] } ], "source": [ "print('Outside, before function: \\t', my_var)\n", "change_var(my_var)\n", "print('Outside, after function: \\t', my_var)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Functions II\n", "\n", "- more on user-defined functions\n", " - docstrings\n", " - default values\n", "- methods\n", " - string, list, & dictionary\n", " - in place vs not in place\n", " - relationship to functions" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Docstrings\n", "\n", "When writing functions, it's often helpful to include information about what the function does.\n", "\n", "These are specified by text within triple quotes in the first line after your function is defined." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def my_func(my_dictionary):\n", " \"\"\"return list of dictionary values or something a bit more precise/lengthy\"\"\"\n", " ## comment that is not very helpful\n", " output = []\n", "\n", " for item in my_dictionary:\n", " value = my_dictionary[item]\n", " output.append(value)\n", " \n", " return output" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "my_func?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Default Values" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "
\n", "Function parameters can also take default values. This makes some parameters optional, as they take a default value if not otherwise specified.\n", "
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Default Value Functions\n", "\n", "Specify a default value in a function by doing an assignment within the function definition." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Create a function, that has a default values for a parameter\n", "def exponentiate(number, exponent = 2): \n", " return number**exponent" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use the function, using default value\n", "exponentiate(2)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Call the function, over-riding default value with something else\n", "# python assumes values are in order of parameters specified in definition\n", "exponentiate(3)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# you can always state this explicitly\n", "exponentiate(number = 2, exponent = 3)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Positional vs. Keyword Arguments" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "Arguments to a function can be indicated by either position or keyword.\n", "
" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Positional arguments use the position to infer which argument each value relates to\n", "exponentiate(2, 3)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Keyword arguments are explicitly named as to which argument each value relates to\n", "exponentiate(number = 2, exponent = 3)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exponentiate(exponent = 3, number = 2)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "SyntaxError", "evalue": "positional argument follows keyword argument (, line 3)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m exponentiate(number = 2, 3)\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m positional argument follows keyword argument\n" ] } ], "source": [ "# Note: once you have a keyword argument, you can't have other positional arguments afterwards\n", "# this cell will produce an error\n", "exponentiate(number = 2, 3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# this may look like what we did above\n", "# but there is a difference between executing and defining\n", "# when specifying functions, including a value for one parameter\n", "# is to set default values for a paramater\n", "def exponentiate(number, exponent = 2): \n", " return number**exponent" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Methods" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "Methods are functions that are defined and called directly on an object. \n", "
\n", "\n", "
\n", "For our purposes, objects are any data variable. \n", "
" ] }, { "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": 14, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4]\n" ] } ], "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": 15, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "AttributeError", "evalue": "'str' object has no attribute 'append'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;31m# this will error with a string\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mmy_string\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'cogs18'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mmy_string\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[0;34m(\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;31mAttributeError\u001b[0m: 'str' object has no attribute 'append'" ] } ], "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": 16, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# The `is_integer()` method, defined on floats\n", "my_float = 12.2\n", "my_float.is_integer()" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "ename": "AttributeError", "evalue": "'int' object has no attribute 'is_integer'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;31m# this code will produce an error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0mmy_int\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m12\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mmy_int\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mis_integer\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;31mAttributeError\u001b[0m: 'int' object has no attribute 'is_integer'" ] } ], "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": 18, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'abc'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Make a string all lower case\n", "'aBc'.lower()" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'ABC'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Make a string all upper case\n", "'aBc'.upper()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "'Python is great'" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Capitalize a string\n", "'python is great'.capitalize()" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "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": [ "## 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": 25, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "[16, 33, 40, 88]" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# sort sorts integers in numerical orders\n", "ints = [16, 88, 33, 40]\n", "ints.sort()\n", "ints" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "[16, 33, 40, 88, 2]" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# append adds to the end of a list\n", "ints.append(2)\n", "ints" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "[16, 33, 88, 2]" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# remove value from list\n", "ints.remove(40)\n", "ints" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "[2, 88, 33, 16]" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# reverse order of list\n", "ints.reverse()\n", "ints" ] }, { "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": 30, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "dict_keys(['brand', 'model', 'year'])" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "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": 31, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "M5\n" ] } ], "source": [ "# get returns the value of a specified key\n", "mod = car.get('model')\n", "\n", "print(mod)" ] }, { "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": 32, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'brand': 'BMW', 'model': 'M5', 'year': 2019, 'color': 'Black'}\n" ] } ], "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": [ "### Methods: In Place vs Not In Place" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "
\n", "Some methods update the object directly (in place), whereas others return an updated version of the input. \n", "
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### List methods that are in place" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "scrolled": true, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['c', 'b', 'a']\n" ] } ], "source": [ "# Reverse a list\n", "my_list = ['a', 'b', 'c']\n", "my_list.reverse()\n", "\n", "print(my_list)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[-1, 3, 13]\n" ] } ], "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": 37, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "{'brand': 'BMW', 'color': 'Black', 'model': 'M5', 'year': 2019}" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "car" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# Return the keys in the dictionary\n", "out = car.keys() " ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "dict_keys(['brand', 'model', 'year', 'color'])\n" ] } ], "source": [ "# print keys\n", "print(type(out))\n", "print(out)" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "{'brand': 'BMW', 'model': 'M5', 'year': 2019, 'color': 'Black'}\n" ] } ], "source": [ "# car has not changed\n", "print(type(car))\n", "print(car)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "dict_values(['BMW', 'M5', 2019, 'Black'])" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "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": 42, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "data": { "text/plain": [ "['__add__',\n", " '__class__',\n", " '__contains__',\n", " '__delattr__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__iter__',\n", " '__le__',\n", " '__len__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " 'capitalize',\n", " 'casefold',\n", " 'center',\n", " 'count',\n", " 'encode',\n", " 'endswith',\n", " 'expandtabs',\n", " 'find',\n", " 'format',\n", " 'format_map',\n", " 'index',\n", " 'isalnum',\n", " 'isalpha',\n", " 'isdecimal',\n", " 'isdigit',\n", " 'isidentifier',\n", " 'islower',\n", " 'isnumeric',\n", " 'isprintable',\n", " 'isspace',\n", " 'istitle',\n", " 'isupper',\n", " 'join',\n", " 'ljust',\n", " 'lower',\n", " 'lstrip',\n", " 'maketrans',\n", " 'partition',\n", " 'replace',\n", " 'rfind',\n", " 'rindex',\n", " 'rjust',\n", " 'rpartition',\n", " 'rsplit',\n", " 'rstrip',\n", " 'split',\n", " 'splitlines',\n", " 'startswith',\n", " 'strip',\n", " 'swapcase',\n", " 'title',\n", " 'translate',\n", " 'upper',\n", " 'zfill']" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "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": [ "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": "slide" } }, "source": [ "### Method / Function Comparison Example" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n" ] } ], "source": [ "my_float = 11.0\n", "\n", "# Method call\n", "print(my_float.is_integer())\n", "\n", "# Function call\n", "# Note: `is_integer` is part of the float variable type, which is why we access it from there \n", "print(float.is_integer(my_float))" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# method documentation\n", "float.is_integer?" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "# function documentation\n", "type?" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### `is_integer`\n", "\n", "You _could_ write a function to check whether a float was an integer and use it as a function (rather than the method `.is_integer()`) ...and we know how to do that!" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def is_integer(my_float):\n", " \n", " if my_float % 1 == 0:\n", " is_int = True\n", " else:\n", " is_int = False\n", " \n", " return is_int" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11.0\n" ] }, { "data": { "text/plain": [ "True" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "print(my_float)\n", "is_integer(my_float)" ] } ], "metadata": { "celltoolbar": "Slideshow", "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.6.7" } }, "nbformat": 4, "nbformat_minor": 2 }