{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Procedural programming in python\n", "\n", "## Topics\n", "* Tuples, lists and dictionaries\n", "* Flow control, part 1\n", " * If\n", " * For\n", " * range() function\n", "* Some hacky hack time\n", "* Flow control, part 2\n", " * Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tuples\n", "\n", "Let's begin by creating a tuple called `my_tuple` that contains three elements." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple = ('I', 'like', 'cake')\n", "my_tuple" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tuples are simple containers for data. They are ordered, meaining the order the elements are in when the tuple is created are preserved. We can get values from our tuple by using array indexing, similar to what we were doing with pandas." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Recall that Python indexes start at 0. So the first element in a tuple is 0 and the last is array length - 1. You can also address from the `end` to the `front` by using negative (`-`) indexes, e.g." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple[-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also access a range of elements, e.g. the first two, the first three, by using the `:` to expand a range. This is called ``slicing``." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple[0:2]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple[0:3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What do you notice about how the upper bound is referenced?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Without either end, the ``:`` expands to the entire list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple[1:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple[:-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple[:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tuples have a key feature that distinguishes them from other types of object containers in Python. They are _immutable_. This means that once the values are set, they cannot change." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple[2]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So what happens if I decide that I really prefer pie over cake?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#my_tuple[2] = 'pie'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Facts about tuples:\n", "* You can't add elements to a tuple. Tuples have no append or extend method.\n", "* You can't remove elements from a tuple. Tuples have no remove or pop method.\n", "* You can also use the in operator to check if an element exists in the tuple.\n", "\n", "So then, what are the use cases of tuples? \n", "* Speed\n", "* `Write-protects` data that other pieces of code should not alter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can alter the value of a tuple variable, e.g. change the tuple it holds, but you can't modify it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_tuple = ('I', 'love', 'pie')\n", "my_tuple" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There is a really handy operator ``in`` that can be used with tuples that will return `True` if an element is present in a tuple and `False` otherwise." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'love' in my_tuple" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, tuples can contain different types of data, not just strings." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import math\n", "my_second_tuple = (42, 'Elephants', 'ate', math.pi)\n", "my_second_tuple" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Numerical operators work... Sort of. What happens when you add? \n", "\n", "``my_second_tuple + 'plus'``" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Not what you expects? What about adding two tuples?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_second_tuple + my_tuple" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other operators: -, /, *" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Questions about tuples before we move on?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "### Lists\n", "\n", "Let's begin by creating a list called `my_list` that contains three elements." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_list = ['I', 'like', 'cake']\n", "my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "At first glance, tuples and lists look pretty similar. Notice the lists use '[' and ']' instead of '(' and ')'. But indexing and refering to the first entry as 0 and the last as -1 still works the same." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_list[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_list[-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_list[0:3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists, however, unlike tuples, are mutable. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_list[2] = 'pie'\n", "my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Multiple elements in the list can even be changed at once!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_list[1:] = ['love', 'puppies']\n", "my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can still use the `in` operator." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'puppies' in my_list" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'kittens' in my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So when to use a tuple and when to use a list?\n", "\n", "* Use a list when you will modify it after it is created?\n", "\n", "Ways to modify a list? You have already seen by index. Let's start with an empty list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_new_list = []\n", "my_new_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can add to the list using the append method on it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_new_list.append('Now')\n", "my_new_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use the `+` operator to create a longer list by adding the contents of two lists together." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_new_list + my_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the useful things to know about a list how many elements are in it. This can be found with the `len` function." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "len(my_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some other handy functions with lists:\n", "* max\n", "* min" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes you have a tuple and you need to make it a list. You can `cast` the tuple to a list with ``list(my_tuple)``" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list(my_tuple)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What in the above told us it was a list? \n", "\n", "You can also use the ``type`` function to figure out the type." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(tuple)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(list(my_tuple))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There are other useful methods on lists, including:\n", "\n", "| methods | description |\n", "|---|---|\n", "| list.append(obj) | Appends object obj to list |\n", "| list.count(obj)| Returns count of how many times obj occurs in list |\n", "| list.extend(seq) | Appends the contents of seq to list |\n", "| list.index(obj) | Returns the lowest index in list that obj appears |\n", "| list.insert(index, obj) | Inserts object obj into list at offset index |\n", "| list.pop(obj=list[-1]) | Removes and returns last object or obj from list |\n", "| list.remove(obj) | Removes object obj from list |\n", "| list.reverse() | Reverses objects of list in place |\n", "| list.sort([func]) | Sort objects of list, use compare func, if given |\n", "\n", "Try some of them now.\n", "\n", "```\n", "my_list.count('I')\n", "my_list\n", "\n", "my_list.append('I')\n", "my_list\n", "\n", "my_list.count('I')\n", "my_list\n", "\n", "#my_list.index(42)\n", "\n", "my_list.index('puppies')\n", "my_list\n", "\n", "my_list.insert(my_list.index('puppies'), 'furry')\n", "my_list\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_list.count('I')\n", "my_list\n", "\n", "my_list.append('I')\n", "my_list\n", "\n", "my_list.count('I')\n", "my_list\n", "\n", "#my_list.index(42)\n", "\n", "my_list.index('puppies')\n", "my_list\n", "\n", "my_list.insert(my_list.index('puppies'), 'furry')\n", "my_list\n", "\n", "my_list.pop()\n", "my_list\n", "\n", "my_list.remove('puppies')\n", "my_list\n", "\n", "my_list.append('cabbages')\n", "my_list" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Any questions about lists before we move on?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "### Dictionaries\n", "\n", "Dictionaries are similar to tuples and lists in that they hold a collection of objects. Dictionaries, however, allow an additional indexing mode: keys. Think of a real dictionary where the elements in it are the definitions of the words and the keys to retrieve the entries are the words themselves.\n", "\n", "| word | definition |\n", "|------|------------|\n", "| tuple | An immutable collection of ordered objects |\n", "| list | A mutable collection of ordered objects |\n", "| dictionary | A mutable collection of named objects |\n", "\n", "Let's create this data structure now. Dictionaries, like tuples and elements use a unique referencing method, '{' and its evil twin '}'." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_dict = { 'tuple' : 'An immutable collection of ordered objects',\n", " 'list' : 'A mutable collection of ordered objects',\n", " 'dictionary' : 'A mutable collection of objects' }\n", "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We access items in the dictionary by name, e.g. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_dict['dictionary']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Since the dictionary is mutable, you can change the entries." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_dict['dictionary'] = 'A mutable collection of named objects'\n", "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that ordering is not preserved!\n", "#### As of Python 3.7 the ordering is garunteed to be insertion order but that does not mean alphabetical or otherwise sorted.\n", "\n", "And we can add new items to the list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_dict['cabbage'] = 'Green leafy plant in the Brassica family'\n", "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To delete an entry, we can't just set it to ``None``" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_dict['cabbage'] = None\n", "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To delete it propery, we need to pop that specific entry." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_dict.pop('cabbage', None)\n", "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can use other objects as names, but that is a topic for another time. You can mix and match key types, e.g." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_new_dict = {}\n", "my_new_dict[1] = 'One'\n", "my_new_dict['42'] = 42\n", "my_new_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can get a list of keys in the dictionary by using the ``keys`` method." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_dict.keys()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly the contents of the dictionary with the ``items`` method." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_dict.items()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can use the keys list for fun stuff, e.g. with the ``in`` operator." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'dictionary' in my_dict.keys()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is a synonym for `in my_dict`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'dictionary' in my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice, it doesn't work for elements." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'A mutable collection of ordered objects' in my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other dictionary methods:\n", "\n", "| methods | description |\n", "|---|---|\n", "| dict.clear() | Removes all elements from dict |\n", "| dict.get(key, default=None) | For ``key`` key, returns value or ``default`` if key doesn't exist in dict | \n", "| dict.items() | Returns a list of dicts (key, value) tuple pairs | \n", "| dict.keys() | Returns a list of dictionary keys |\n", "| dict.setdefault(key, default=None) | Similar to get, but set the value of key if it doesn't exist in dict |\n", "| dict.update(dict2) | Add the key / value pairs in dict2 to dict |\n", "| dict.values | Returns a list of dictionary values|\n", "\n", "Feel free to experiment..." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", "## Flow control\n", "\n", "Flow control figure\n", "\n", "Flow control refers how to programs do loops, conditional execution, and order of functional operations. Let's start with conditionals, or the venerable ``if`` statement.\n", "\n", "Let's start with a simple list of instructors for these classes." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "instructors = ['Dave', 'Erin', 'Murf the Clown']\n", "instructors" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### If\n", "If statements can be use to execute some lines or block of code if a particular condition is satisfied. E.g. Let's print something based on the entries in the list." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if 'Murf the Clown' in instructors:\n", " print('#fakeinstructor')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Usually we want conditional logic on both sides of a binary condition, e.g. some action when ``True`` and some when ``False``" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if 'Murf the Clown' in instructors:\n", " print('There are fake names for class instructors in your list!')\n", "else:\n", " print(\"Nothing to see here\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There is a special do nothing word: `pass` that skips over some arm of a conditional, e.g." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if 'Erin' in instructors:\n", " print(\"Congratulations! Erin is teaching, your class won't stink!\")\n", "else:\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Note_: what have you noticed in this session about quotes? What is the difference between ``'`` and ``\"``?\n", "\n", "\n", "Another simple example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "if True is False:\n", " print(\"I'm so confused\")\n", "else:\n", " print(\"Everything is right with the world\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is always good practice to handle all cases explicity. `Conditional fall through` is a common source of bugs.\n", "\n", "Sometimes we wish to test multiple conditions. Use `if`, `elif`, and `else`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_favorite = 'pie'\n", "\n", "if my_favorite == 'cake':\n", " print(\"He likes cake! I'll start making a double chocolate velvet cake right now!\")\n", "elif my_favorite == 'pie':\n", " print(\"He likes pie! I'll start making a cherry pie right now!\")\n", "else:\n", " print(\"He likes \" + my_favorite + \". I don't know how to make that.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Conditionals can take ``and`` and ``or`` and ``not``. E.g." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_favorite = 'pie'\n", "\n", "if my_favorite == 'cake' or my_favorite == 'pie':\n", " print(my_favorite + \" : I have a recipe for that!\")\n", "else:\n", " print(\"Ew! Who eats that?\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## For\n", "\n", "For loops are the standard loop, though `while` is also common. For has the general form:\n", "```\n", "for items in list:\n", " do stuff\n", "```\n", "\n", "For loops and collections like tuples, lists and dictionaries are natural friends." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for instructor in instructors:\n", " print(instructor)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can combine loops and conditionals:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for instructor in instructors:\n", " if instructor.endswith('Clown'):\n", " print(instructor + \" doesn't sound like a real instructor name!\")\n", " else:\n", " print(instructor + \" is so smart... all those gooey brains!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dictionaries can use the `keys` method for iterating." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for key in my_dict.keys():\n", " if len(key) > 5:\n", " print(my_dict[key])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### range()\n", "\n", "Since for operates over lists, it is common to want to do something like:\n", "```\n", "NOTE: C-like\n", "for (i = 0; i < 3; ++i) {\n", " print(i);\n", "}\n", "```\n", "\n", "The Python equivalent is:\n", "\n", "```\n", "for i in [0, 1, 2]:\n", " do something with i\n", "```\n", "\n", "What happens when the range you want to sample is big, e.g.\n", "```\n", "NOTE: C-like\n", "for (i = 0; i < 1000000000; ++i) {\n", " print(i);\n", "}\n", "```\n", "\n", "That would be a real pain in the rear to have to write out the entire list from 1 to 1000000000.\n", "\n", "Enter, the `range()` function. E.g.\n", " ```range(3) is [0, 1, 2]```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "range(3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that Python (in the newest versions, e.g. 3+) has an object type that is a range. This saves memory and speeds up calculations vs. an explicit representation of a range as a list - but it can be automagically converted to a list on the fly by Python. To show the contents as a `list` we can use the type case like with the tuple above.\n", "\n", "Sometimes, in older Python docs, you will see `xrange`. This used the range object back in Python 2 and `range` returned an actual list. Beware of this!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "list(range(3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remember earlier with slicing, the syntax `:3` meant `[0, 1, 2]`? Well, the same upper bound philosophy applies here.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for index in range(3):\n", " instructor = instructors[index]\n", " if instructor.endswith('Clown'):\n", " print(instructor + \" doesn't sound like a real instructor name!\")\n", " else:\n", " print(instructor + \" is so smart... all those gooey brains!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This would probably be better written as" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for index in range(len(instructors)):\n", " instructor = instructors[index]\n", " if instructor.endswith('Clown'):\n", " print(instructor + \" doesn't sound like a real instructor name!\")\n", " else:\n", " print(instructor + \" is so smart... all those gooey brains!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But in all, it isn't very Pythonesque to use indexes like that (unless you have another reason in the loop) and you would opt instead for the `instructor in instructors` form. \n", "\n", "More often, you are doing something with the numbers that requires them to be integers, e.g. math." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sum = 0\n", "for i in range(10):\n", " sum += i\n", "print(sum)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### For loops can be nested\n", "\n", "_Note_: for more on formatting strings, see: [https://pyformat.info](https://pyformat.info)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(1, 4):\n", " for j in range(1, 4):\n", " print('%d * %d = %d' % (i, j, i*j)) # Note string formatting here, %d means an integer" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### You can exit loops early if a condition is met:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(10):\n", " if i == 4:\n", " break\n", "i" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### You can skip stuff in a loop with `continue`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sum = 0\n", "for i in range(10):\n", " if (i == 5):\n", " continue\n", " else:\n", " sum += i\n", "print(sum)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### There is a unique language feature call ``for...else``" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sum = 0\n", "for i in range(10):\n", " sum += i\n", "else:\n", " print('final i = %d, and sum = %d' % (i, sum))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### You can iterate over letters in a string" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "my_string = \"SEDS\"\n", "for c in my_string:\n", " print(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Functions\n", "\n", "For loops let you repeat some code for every item in a list. Functions are similar in that they run the same lines of code for new values of some variable. They are different in that functions are not limited to looping over items.\n", "\n", "Functions are a critical part of writing easy to read, reusable code.\n", "\n", "Create a function like:\n", "```\n", "def function_name (parameters):\n", " \"\"\"\n", " optional docstring\n", " \"\"\"\n", " function expressions\n", " return [variable]\n", "```\n", "\n", "_Note:_ Sometimes I use the word argument in place of parameter.\n", "\n", "Here is a simple example. It prints a string that was passed in and returns nothing." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def print_string(str):\n", " \"\"\"This prints out a string passed as the parameter.\"\"\"\n", " print(str)\n", " return" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To call the function, use:\n", "```\n", "print_string(\"Dave is awesome!\")\n", "```\n", "\n", "_Note:_ The function has to be defined before you can call it!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print_string(\"Dave is awesome!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you don't provide an argument or too many, you get an error." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Parameters (or arguments) in Python are all passed by reference. This means that if you modify the parameters in the function, they are modified outside of the function.\n", "\n", "See the following example:\n", "\n", "```\n", "def change_list(my_list):\n", " \"\"\"This changes a passed list into this function\"\"\"\n", " my_list.append('four');\n", " print('list inside the function: ', my_list)\n", " return\n", "\n", "my_list = [1, 2, 3];\n", "print('list before the function: ', my_list)\n", "change_list(my_list);\n", "print('list after the function: ', my_list)\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def change_list(my_list):\n", " \"\"\"This changes a passed list into this function\"\"\"\n", " my_list.append('four');\n", " print('list inside the function: ', my_list)\n", " return\n", "\n", "my_list = [1, 2, 3];\n", "print('list before the function: ', my_list)\n", "change_list(my_list);\n", "print('list after the function: ', my_list)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Variables have scope: `global` and `local`\n", "\n", "In a function, new variables that you create are not saved when the function returns - these are `local` variables. Variables defined outside of the function can be accessed but not changed - these are `global` variables, _Note_ there is a way to do this with the `global` keyword. Generally, the use of `global` variables is not encouraged, instead use parameters.\n", "\n", "```\n", "my_global_1 = 'bad idea'\n", "my_global_2 = 'another bad one'\n", "my_global_3 = 'better idea'\n", "\n", "def my_function():\n", " print(my_global)\n", " my_global_2 = 'broke your global, man!'\n", " global my_global_3\n", " my_global_3 = 'still a better idea'\n", " return\n", " \n", "my_function()\n", "print(my_global_2)\n", "print(my_global_3)\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In general, you want to use parameters to provide data to a function and return a result with the `return`. E.g.\n", "\n", "```\n", "def sum(x, y):\n", " my_sum = x + y\n", " return my_sum\n", "```\n", "\n", "If you are going to return multiple objects, what data structure that we talked about can be used? Give and example below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Parameters have four different types:\n", "\n", "| type | behavior |\n", "|------|----------|\n", "| required | positional, must be present or error, e.g. `my_func(first_name, last_name)` |\n", "| keyword | position independent, e.g. `my_func(first_name, last_name)` can be called `my_func(first_name='Dave', last_name='Beck')` or `my_func(last_name='Beck', first_name='Dave')` |\n", "| default | keyword params that default to a value if not provided |\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def print_name(first, last='the Clown'):\n", " print('Your name is %s %s' % (first, last))\n", " return" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Play around with the above function." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Functions can contain any code that you put anywhere else including:\n", "* if...elif...else\n", "* for...else\n", "* while\n", "* other function calls" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def print_name_age(first, last, age):\n", " print_name(first, last)\n", " print('Your age is %d' % (age))\n", " if age > 35:\n", " print('You are really old.')\n", " return" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print_name_age(age=45, last='Beck', first='Dave')" ] } ], "metadata": { "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.9.12" } }, "nbformat": 4, "nbformat_minor": 1 }