{"cells": [{"cell_type": "markdown", "id": "16c7c756", "metadata": {}, "source": ["# DS2500 Lesson 3\n", "Jan 20, 2023\n", "\n", "Content:\n", "- Sets\n", "- Loops (zip, enumerate, itertools)\n", "- String Manipulation\n", "\n", "Admin:\n", "- hw0 released today\n", " - review hw, autograder & points description\n", "- lab0 next week\n", " - will feel like `process_rps()` from last class's ICA (in groups)\n"]}, {"cell_type": "markdown", "id": "5b82ab91", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["# Sets\n", "\n", "[official documentation on Sets](https://docs.python.org/3/library/stdtypes.html#set)\n", "\n", "A python set (like the math object) is an unordered collection of objects.\n", "\n", "They're mutable.\n"]}, {"cell_type": "code", "execution_count": 2, "id": "561d3f65", "metadata": {}, "outputs": [], "source": ["# build a set\n", "some_set = {1, 'a', 'b'}\n"]}, {"cell_type": "code", "execution_count": 3, "id": "3c5d94ba", "metadata": {"scrolled": true}, "outputs": [{"data": {"text/plain": ["{1, 'a', 'b', 'c'}"]}, "execution_count": 3, "metadata": {}, "output_type": "execute_result"}], "source": ["# add item to existing set\n", "some_set.add('c')\n", "some_set\n"]}, {"cell_type": "code", "execution_count": 4, "id": "ecbfb6f1", "metadata": {}, "outputs": [{"data": {"text/plain": ["{1, 'a', 'b', 'c'}"]}, "execution_count": 4, "metadata": {}, "output_type": "execute_result"}], "source": ["# you may .add() an item which is already in the set ... but doesn't do much ...\n", "# (an item is either in the set or it isn't ... can't be in set \"twice\")\n", "some_set.add('c')\n", "some_set\n"]}, {"cell_type": "code", "execution_count": 5, "id": "80818596", "metadata": {"scrolled": false}, "outputs": [{"data": {"text/plain": ["{'a', 'b'}"]}, "execution_count": 5, "metadata": {}, "output_type": "execute_result"}], "source": ["# similarly\n", "{'a', 'a', 'b'}\n"]}, {"cell_type": "code", "execution_count": 6, "id": "23e075c5", "metadata": {}, "outputs": [{"data": {"text/plain": ["{'a', 'b', 'c'}"]}, "execution_count": 6, "metadata": {}, "output_type": "execute_result"}], "source": ["# you can remove items from a set\n", "some_set.remove(1) \n", "some_set\n"]}, {"cell_type": "code", "execution_count": 7, "id": "86fc8808", "metadata": {}, "outputs": [{"data": {"text/plain": ["False"]}, "execution_count": 7, "metadata": {}, "output_type": "execute_result"}], "source": ["# testing if object is in a set (fast, this is what sets are designed to do)\n", "1 in some_set\n"]}, {"cell_type": "code", "execution_count": 8, "id": "1b68b30d", "metadata": {}, "outputs": [{"data": {"text/plain": ["True"]}, "execution_count": 8, "metadata": {}, "output_type": "execute_result"}], "source": ["# sets aren't ordered\n", "{'a', 'b'} == {'b', 'a'}\n"]}, {"cell_type": "code", "execution_count": 9, "id": "d0b49e38", "metadata": {}, "outputs": [{"data": {"text/plain": ["{1, 2, 'a', 'b', 'x', 'y', 'z'}"]}, "execution_count": 9, "metadata": {}, "output_type": "execute_result"}], "source": ["# set operation: union\n", "{1, 'a', 'b'} | {2, 'x', 'y', 'z'}\n"]}, {"cell_type": "code", "execution_count": 10, "id": "273eb755", "metadata": {}, "outputs": [{"data": {"text/plain": ["{1}"]}, "execution_count": 10, "metadata": {}, "output_type": "execute_result"}], "source": ["# ste operation: intersection\n", "{1, 'a' , 'b'} & {1, 'x', 'y', 'z'}\n"]}, {"cell_type": "code", "execution_count": 11, "id": "1f7f2c9f", "metadata": {}, "outputs": [{"data": {"text/plain": ["{'a', 'b'}"]}, "execution_count": 11, "metadata": {}, "output_type": "execute_result"}], "source": ["# set operation: difference\n", "{1, 'a', 'b'} - {1, 'x', 'y', 'z'}\n"]}, {"cell_type": "markdown", "id": "458dbeef", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["# Building an empty set\n"]}, {"cell_type": "code", "execution_count": 53, "id": "76760410", "metadata": {}, "outputs": [{"data": {"text/plain": ["dict"]}, "execution_count": 53, "metadata": {}, "output_type": "execute_result"}], "source": ["# is this an empty set or an empty dictionary?\n", "x = {}\n", "type(x)\n"]}, {"cell_type": "code", "execution_count": 54, "id": "365fcede", "metadata": {}, "outputs": [{"data": {"text/plain": ["set"]}, "execution_count": 54, "metadata": {}, "output_type": "execute_result"}], "source": ["# this is how to build an empty set\n", "x = set()\n", "type(x)\n"]}, {"cell_type": "code", "execution_count": 55, "id": "17c249bb", "metadata": {}, "outputs": [{"data": {"text/plain": ["dict"]}, "execution_count": 55, "metadata": {}, "output_type": "execute_result"}], "source": ["# preference: build empty dictionaries explicitly like this too\n", "x = dict()\n", "type(x)\n"]}, {"cell_type": "markdown", "id": "6381ee8f", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["# Iteration (loops), allow us to repeat code without copying and pasting\n", "- copying and pasting code makes it really challenging to modiyf code when needed\n", "- copying and pasting code makes it really challenging to modiyf code when needed\n", "- copying and pasting code makes it really challenging to modiyf code when needed\n", "- copying and pasting code makes it really challenging to modiyf code when needed\n", "- copying and pasting code makes it really challenging to modiyf code when needed\n"]}, {"cell_type": "markdown", "id": "c0904aa6", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["## `range()`\n", "`range()` is a python function which counts sequential values (0, 1, 2, 3, ...) \n", "\n", "[official range() documentation](https://docs.python.org/3/library/functions.html#func-range)\n"]}, {"cell_type": "code", "execution_count": 12, "id": "4d7e495e", "metadata": {}, "outputs": [{"data": {"text/plain": ["range(0, 10)"]}, "execution_count": 12, "metadata": {}, "output_type": "execute_result"}], "source": ["# notice: calling range() provides us a range object\n", "range(10)\n"]}, {"cell_type": "code", "execution_count": 13, "id": "a5cfb63b", "metadata": {}, "outputs": [{"data": {"text/plain": ["[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"]}, "execution_count": 13, "metadata": {}, "output_type": "execute_result"}], "source": ["# to see whats inside that range, we may type-cast to a list:\n", "list(range(10))\n"]}, {"cell_type": "code", "execution_count": 14, "id": "f27ac2ef", "metadata": {}, "outputs": [{"data": {"text/plain": ["[1, 3, 5, 7, 9]"]}, "execution_count": 14, "metadata": {}, "output_type": "execute_result"}], "source": ["# range(start_idx, stop_idx, step_size)\n", "# notice: range can use the same slicing index we previously covered\n", "list(range(1, 11, 2))\n"]}, {"cell_type": "markdown", "id": "0b17a24f", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["## Iteration: For Loops\n", "For loops run the same block of code multiple times, allowing us to avoid copy-pasting code.\n", "\n"]}, {"cell_type": "code", "execution_count": 15, "id": "9f408f12", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["0\n", "1\n", "4\n", "9\n", "16\n"]}], "source": ["# verbose code to print square of first n integers\n", "print(0**2)\n", "print(1**2)\n", "print(2**2)\n", "print(3**2)\n", "print(4**2)\n"]}, {"cell_type": "code", "execution_count": 16, "id": "40bdd882", "metadata": {}, "outputs": [{"data": {"text/plain": ["[0, 1, 2]"]}, "execution_count": 16, "metadata": {}, "output_type": "execute_result"}], "source": ["list(range(3))\n"]}, {"cell_type": "code", "execution_count": 17, "id": "5b417e62", "metadata": {"scrolled": true}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["0\n", "1\n", "2\n"]}], "source": ["# note to self: trace this with debugger in pycharm\n", "for idx in range(3):\n", " print(idx)\n"]}, {"cell_type": "markdown", "id": "97ee2b5b", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["# In Class Assignment A\n", "\n", "Use `input()` to ask:\n", "- user0 for their 5 favorite ice cream flavors \n", "- user1 for their 5 favorite ice cream flavors\n", "\n", "Print a message which tells both users\n", "- how many favorite colors they have in common\n", " - capitalization counts: \"Chocolate\" is a different ice cream than \"chocolate\"\n", "- (if any favorite color exists): print them\n"]}, {"cell_type": "code", "execution_count": null, "id": "c92ccde4", "metadata": {}, "outputs": [], "source": ["\n"]}, {"cell_type": "code", "execution_count": null, "id": "938af103", "metadata": {}, "outputs": [], "source": ["\n"]}, {"cell_type": "markdown", "id": "3f68a934", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["### Iterating through an ordered collection: (list, tuple & str)\n", "We could loop over the items via `range()` and index into the object:\n"]}, {"cell_type": "code", "execution_count": 18, "id": "8c5ab915", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["a\n", "b\n", "c\n", "d\n"]}], "source": ["# a cumbersome way to iterate through a list\n", "some_list = ['a', 'b', 'c', 'd']\n", "num_items = len(some_list)\n", "\n", "for idx in range(num_items):\n", " item = some_list[idx]\n", " print(item)\n"]}, {"cell_type": "markdown", "id": "cca3781e", "metadata": {}, "source": ["The index allows us to access each item, but our code looks a bit more cumbersome.\n", "\n", "Python allows you to iterate through all the items in the list itself, no indexing needed:\n"]}, {"cell_type": "code", "execution_count": 19, "id": "91ac9847", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["a\n", "b\n", "c\n", "d\n"]}], "source": ["# iterate through the list, skip the complexity of indexing\n", "some_list = ['a', 'b', 'c', 'd']\n", "for item in some_list:\n", " print(item)\n"]}, {"cell_type": "code", "execution_count": 20, "id": "4761ce74", "metadata": {"scrolled": true}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["a\n", "e\n", "i\n", "o\n", "u\n"]}], "source": ["# you can iterate on strings too\n", "for vowel in 'aeiou':\n", " print(vowel)\n"]}, {"cell_type": "code", "execution_count": 21, "id": "3c255286", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["hello\n", "this\n", "is\n", "a\n", "tuple\n", "of\n", "strings\n"]}], "source": ["# or tuples\n", "for item in ('hello', 'this', 'is', 'a', 'tuple', 'of', 'strings'):\n", " print(item)\n"]}, {"cell_type": "markdown", "id": "c76cc69c", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["### Iterating through an un-ordered collection: sets\n", "We couldn't possibly iterate by index, there is no \"first\" item in a set or dictionary!\n"]}, {"cell_type": "code", "execution_count": 22, "id": "7545a1e4", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["1\n", "a\n", "b\n"]}], "source": ["# iterating through a set\n", "some_set = {1, 'a', 'b'}\n", "for item in some_set:\n", " print(item)\n"]}, {"cell_type": "markdown", "id": "04ff338b", "metadata": {}, "source": ["# Warning:\n", "\n", "The order that python iterates through a set and *dictionary may not be consistent across runs!\n", "\n", "- If you need a consistent order for your set ... use a list / tuple\n", "- If you need a consistent order for your dict ... use an [OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict)\n"]}, {"cell_type": "markdown", "id": "0091aaab", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["### Iterating through an un-ordered collection: dict\n"]}, {"cell_type": "code", "execution_count": 23, "id": "e012c106", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["matt\n", "riva\n", "eli\n"]}], "source": ["some_dict = {'matt': 7, 'riva': 7, 'eli':11}\n", "for key in some_dict.keys():\n", " print(key)\n"]}, {"cell_type": "code", "execution_count": 24, "id": "dc7768a4", "metadata": {"scrolled": true}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["7\n", "7\n", "11\n"]}], "source": ["for val in some_dict.values():\n", " print(val)\n"]}, {"cell_type": "code", "execution_count": 56, "id": "a0fd909f", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["matt 7\n", "riva 7\n", "eli 11\n"]}], "source": ["for key, val in some_dict.items():\n", " print(key, val)\n"]}, {"cell_type": "markdown", "id": "f140b550", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["## String Formatting\n", "\n", "Python is really great and managing strings.\n", "- lots of great [string methods](https://docs.python.org/3/library/stdtypes.html#string-methods)\n", " - tip: it's better to borrow some code than re-build it ... you don't know what you can borrow until you look\n"]}, {"cell_type": "code", "execution_count": 32, "id": "ab261c20", "metadata": {}, "outputs": [{"data": {"text/plain": ["'ASDF'"]}, "execution_count": 32, "metadata": {}, "output_type": "execute_result"}], "source": ["'asdf'.upper()\n"]}, {"cell_type": "code", "execution_count": 33, "id": "5bb4835d", "metadata": {}, "outputs": [{"data": {"text/plain": ["'asdf'"]}, "execution_count": 33, "metadata": {}, "output_type": "execute_result"}], "source": ["'ASDF'.lower()\n"]}, {"cell_type": "code", "execution_count": 34, "id": "4e7fc9f7", "metadata": {}, "outputs": [{"data": {"text/plain": ["'Proper noun'"]}, "execution_count": 34, "metadata": {}, "output_type": "execute_result"}], "source": ["'proper noun'.capitalize()\n"]}, {"cell_type": "code", "execution_count": 35, "id": "285f1f85", "metadata": {}, "outputs": [{"data": {"text/plain": ["3"]}, "execution_count": 35, "metadata": {}, "output_type": "execute_result"}], "source": ["# one of the 'hi' occurances is hiding in \"this\"\n", "'hi! how many times does this string say hi?'.count('hi')\n"]}, {"cell_type": "code", "execution_count": 36, "id": "9be960dd", "metadata": {}, "outputs": [{"data": {"text/plain": ["True"]}, "execution_count": 36, "metadata": {}, "output_type": "execute_result"}], "source": ["'some_file.pdf'.endswith('.pdf')\n"]}, {"cell_type": "code", "execution_count": 37, "id": "b45af1f8", "metadata": {}, "outputs": [{"data": {"text/plain": ["False"]}, "execution_count": 37, "metadata": {}, "output_type": "execute_result"}], "source": ["'some_file.pdf'.startswith('asdf')\n"]}, {"cell_type": "code", "execution_count": 38, "id": "f65e6275", "metadata": {}, "outputs": [{"data": {"text/plain": ["True"]}, "execution_count": 38, "metadata": {}, "output_type": "execute_result"}], "source": ["'123'.isnumeric()\n"]}, {"cell_type": "code", "execution_count": 39, "id": "a9b015d3", "metadata": {}, "outputs": [{"data": {"text/plain": ["'this string had quite a few spaces at the beggining and end before we .strip()-ed it'"]}, "execution_count": 39, "metadata": {}, "output_type": "execute_result"}], "source": ["' this string had quite a few spaces at the beggining and end before we .strip()-ed it '.strip()\n"]}, {"cell_type": "markdown", "id": "7e1e5d80", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["# `Str.replace()`\n", "\n", "This one is so useful it gets its own slide \n"]}, {"cell_type": "code", "execution_count": 40, "id": "8b5c4481", "metadata": {}, "outputs": [{"data": {"text/plain": ["'mi!!i!!ippi'"]}, "execution_count": 40, "metadata": {}, "output_type": "execute_result"}], "source": ["'mississippi'.replace('s', '!')\n"]}, {"cell_type": "code", "execution_count": 41, "id": "00e302fa", "metadata": {}, "outputs": [{"data": {"text/plain": ["'matt was not here'"]}, "execution_count": 41, "metadata": {}, "output_type": "execute_result"}], "source": ["'matt was here'.replace('was', 'was not')\n"]}, {"cell_type": "code", "execution_count": 42, "id": "7d9e6976", "metadata": {}, "outputs": [{"data": {"text/plain": ["'some_file.ipynb'"]}, "execution_count": 42, "metadata": {}, "output_type": "execute_result"}], "source": ["'some_file.pdf'.replace('.pdf', '.ipynb')\n"]}, {"cell_type": "markdown", "id": "cdbd1336", "metadata": {}, "source": ["# `Str.split()` & `Str.join()`\n"]}, {"cell_type": "code", "execution_count": 43, "id": "b0121e13", "metadata": {}, "outputs": [{"data": {"text/plain": ["['I', 'wonder', 'how', 'many', 'words', 'are', 'in', 'this', 'sentence?']"]}, "execution_count": 43, "metadata": {}, "output_type": "execute_result"}], "source": ["# splits a string wherever the input string is found (space in this example)\n", "'I wonder how many words are in this sentence?'.split(' ')\n"]}, {"cell_type": "code", "execution_count": 44, "id": "4769ac15", "metadata": {}, "outputs": [{"data": {"text/plain": ["9"]}, "execution_count": 44, "metadata": {}, "output_type": "execute_result"}], "source": ["# useful, right?\n", "x = 'I wonder how many words are in this sentence?'.split(' ')\n", "len(x)\n"]}, {"cell_type": "code", "execution_count": 45, "id": "9eec5d03", "metadata": {}, "outputs": [{"data": {"text/plain": ["['mi', 'i', 'ippi']"]}, "execution_count": 45, "metadata": {}, "output_type": "execute_result"}], "source": ["# you can .split() on any string, needn't just be one character like the example above\n", "'mississippi'.split('ss')\n"]}, {"cell_type": "code", "execution_count": 46, "id": "989c39cd", "metadata": {}, "outputs": [{"data": {"text/plain": ["'a!!b!!c'"]}, "execution_count": 46, "metadata": {}, "output_type": "execute_result"}], "source": ["# join will glue together a list of strings with some other string\n", "# (its the inverse of str.split() shown above)\n", "'!!'.join(['a', 'b', 'c'])\n"]}, {"cell_type": "markdown", "id": "f898741a", "metadata": {}, "source": ["# String Formatting\n", "\n", "Allows you to build a string by inputting variables\n"]}, {"cell_type": "code", "execution_count": 47, "id": "6e3a562c", "metadata": {}, "outputs": [{"data": {"text/plain": ["'hello Eli, how are you today?'"]}, "execution_count": 47, "metadata": {}, "output_type": "execute_result"}], "source": ["name = 'Eli'\n", "f'hello {name}, how are you today?'\n"]}, {"cell_type": "code", "execution_count": 48, "id": "3803b642", "metadata": {}, "outputs": [{"data": {"text/plain": ["'hello, my name is: sally and my favorite number is 1.346'"]}, "execution_count": 48, "metadata": {}, "output_type": "execute_result"}], "source": ["# you can control the number or \n", "name = 'sally'\n", "fav_num = 1.3456789\n", "f'hello, my name is: {name} and my favorite number is {fav_num:.3f}'\n"]}, {"cell_type": "markdown", "id": "67da7cda", "metadata": {}, "source": ["[see this table (scroll down slightly)](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting) for other ways of formatting output, like `'.3f'`\n"]}, {"cell_type": "code", "execution_count": null, "id": "93a5f78d", "metadata": {}, "outputs": [], "source": ["\n"]}, {"cell_type": "markdown", "id": "a618b1a3", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["### In Class Acitivity B:\n", "\n", "My son's favorite song is \"Wheels on the Bus\" ([here's a version done by the legend himself](https://www.youtube.com/watch?v=8d8Vo72Kbrk)). He can't get enough of it, the rest of us certainly can. (Full disclosure, he's a bit older now and into a cartoon which is driving us mad ... but allow me some pedagogical license as \"wheels on the bus\" is a better ICA...)\n", "\n", "\n", "Here's how it goes:\n", "\n", "```\n", "The wheels on the bus goes round and round, round and round, round and round\n", "the wheels on the bus goes round and round ... All through the town.\n", "```\n", "\n", "There is a structure to each verse of the song, if:\n", "\n", "``` python\n", "noun = 'wheels on the bus'\n", "move = 'go round and round'\n", "```\n", "\n", "a verse can be written as:\n", "\n", " The on the bus goes , , \n", " the on the bus go ... All through the town\n", "\n", "\n", "\n", "Using the following table of noun-noise pairs, write a loop which prints all verses according to the pattern above:\n", "\n", "| Noun | Noise |\n", "|-----------------|------------------------------------------|\n", "| Wheels | round and round |\n", "| Babies | wah, wah, wah |\n", "| DS2500 students | we <3 python |\n", "\n", "Together:\n", " - how can we store the noun noise together, as pairs?\n", " - how can we repeat the noise, gluing it together with `', '`?\n", " \n", "(++) rewrite your program to so it takes some input for the number of repetitions of ``. Previously we had assumed it was always 3:\n", "\n", " The on the bus goes , , \n", " \n", "but if your program assigns `num_reps=4` then it will write:\n", "\n", " The on the bus goes , , , \n", " \n", "(++) allow `num_reps` to change per individual noun-noise pair\n"]}, {"cell_type": "code", "execution_count": null, "id": "faabc0c5", "metadata": {}, "outputs": [], "source": ["\n"]}, {"cell_type": "code", "execution_count": null, "id": "7bab863f", "metadata": {}, "outputs": [], "source": ["\n"]}, {"cell_type": "code", "execution_count": 49, "id": "564febc6", "metadata": {"scrolled": true}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["The wheels on the bus go round and round, round and round, round and round, \n", "the wheels on the bus go round and round ... all through the town\n", "\n", "The baby on the bus go wah, wah, wah..., wah, wah, wah..., wah, wah, wah..., \n", "the baby on the bus go wah, wah, wah... ... all through the town\n", "\n", "The DS2500 student on the bus go we <3 python, we <3 python, we <3 python, \n", "the DS2500 student on the bus go we <3 python ... all through the town\n", "\n"]}], "source": ["n_repeat = 3\n", "\n", "noun_noise_dict = {'wheels': 'round and round',\n", " 'baby': 'wah, wah, wah...',\n", " 'DS2500 student': 'we <3 python'}\n", "\n", "for noun, noise in noun_noise_dict.items():\n", " # build verse\n", " verse0 = f'The {noun} on the bus go ' + f'{noise}, ' * n_repeat\n", " verse1 = f'the {noun} on the bus go {noise} ... all through the town'\n", "\n", " # print verse\n", " print(verse0)\n", " print(verse1)\n", " print()\n"]}, {"cell_type": "markdown", "id": "7e49db33", "metadata": {}, "source": ["\n"]}, {"cell_type": "markdown", "id": "729b238e", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["# Iteration: While Loops\n", "\n", "Sometimes you don't know how many times you want the body of a loop to run ahead of time.\n", "\n", "In this case, use a while loop:\n"]}, {"cell_type": "code", "execution_count": 28, "id": "b754fbca", "metadata": {"scrolled": true}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["2\n", "4\n", "8\n", "16\n", "32\n", "64\n", "128\n", "256\n", "512\n", "1024\n", "1024\n"]}], "source": ["# doubles a value until it exceeds 1000\n", "# note to self: trace this in debugger\n", "x = 1\n", "while x < 1000:\n", " x = x * 2\n", " print(x)\n", "print(x)\n"]}, {"cell_type": "markdown", "id": "da8a2533", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["# A While loop problem (give me a `break` here!):\n", "\n", "Ask the user for a 5 character input. Re-query if input doesn't have 5 characters.\n"]}, {"cell_type": "code", "execution_count": null, "id": "59bd7d43", "metadata": {}, "outputs": [], "source": ["x = input('input a 5 character string:')\n", " \n", "while len(x) != 5: \n", " print('invalid input, doesnt have 5 characters')\n", " \n", " x = input('input a 5 character string:')\n", " \n", "x\n"]}, {"cell_type": "markdown", "id": "8a774a2d", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["# `break`ing out of a loop\n", "\n", "`break` will exit the loop at the current position, not running any remaining code in the loop body\n", "\n", "Useful if you want to run some of the loop body before testing if you should stop looping:\n", "\n", "```python\n", "while True:\n", " # some of loop body\n", " \n", " if condition:\n", " # if condition is True, stops while loop\n", " break\n", " \n", " # rest of loop body\n", "```\n"]}, {"cell_type": "code", "execution_count": 29, "id": "859b4e98", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["input a 5 character string:abc\n", "invalid input, doesnt have 5 characters\n", "input a 5 character string:abcde\n"]}, {"data": {"text/plain": ["'abcde'"]}, "execution_count": 29, "metadata": {}, "output_type": "execute_result"}], "source": ["# gets string from user with 5 characters\n", "while True:\n", " x = input('input a 5 character string:')\n", " \n", " if len(x) == 5:\n", " # proper user input given\n", " break\n", " \n", " print('invalid input, doesnt have 5 characters')\n", " \n", "x\n"]}, {"cell_type": "markdown", "id": "6612acc7", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["## In Class Assignment C: \n", "\n", "For every vowel, get a word from the user which contains that vowel, store in a dictionary. Re-query the user if their input doesn't contain the vowel. \n", "\n", "Example output dictionary:\n", "\n", "```python\n", "vowel_dict = {'a': 'apple',\n", " 'e': 'peel',\n", " 'i': 'pineapple',\n", " 'o': 'obtuse',\n", " 'u': 'umbrella'}\n", "```\n", "\n", "### Suggested Milestones (baby steps!):\n", "- build an empty `vowel_dict`\n", "- query for input, add it to vowel_dict (use any key)\n", "- query for input starting with 'a', add it to `vowel_dict`, even if its invalid (use key 'a')\n", "- query for input starting with 'a', add it to `vowel_dict` only if its valid\n", "- query for input starting with 'a', add it to `vowel_dict` only if its valid, otherwise re-query as needed\n", " - see example above\n", "- add a loop to above program so it works for `aeiou`\n", "\n", "## ++ If you have time:\n", "- make it a function\n", " - docstring!\n", "- by default, you function should ask for a word for each vowel ... but allow the user of your function to specify their own list of required characters (not necessarily `'aeiou'`)\n"]}, {"cell_type": "code", "execution_count": null, "id": "d0423043", "metadata": {}, "outputs": [], "source": ["\n"]}, {"cell_type": "code", "execution_count": null, "id": "2c91756a", "metadata": {}, "outputs": [], "source": ["\n"]}, {"cell_type": "code", "execution_count": null, "id": "f1a15d47", "metadata": {}, "outputs": [], "source": ["\n"]}, {"cell_type": "code", "execution_count": 50, "id": "fe8e631a", "metadata": {"slideshow": {"slide_type": "slide"}}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["please input a word with lettera: apple\n", "please input a word with lettere: emu\n", "please input a word with letteri: iguana\n", "please input a word with lettero: poodle\n", "please input a word with letteru: umbrella\n"]}, {"data": {"text/plain": ["{'a': 'apple', 'e': 'emu', 'i': 'iguana', 'o': 'poodle', 'u': 'umbrella'}"]}, "execution_count": 50, "metadata": {}, "output_type": "execute_result"}], "source": ["str_vowel = 'aeiou'\n", "\n", "vowel_dict = dict()\n", "for vowel in str_vowel:\n", " \n", " while True:\n", " # collect input from user\n", " str_input = input('please input a word with letter ' + vowel + ': ')\n", " \n", " if vowel in str_input:\n", " # user input is appropriate, store it\n", " vowel_dict[vowel] = str_input\n", " break\n", "\n", " # user input inappropriate, re-query user\n", " print('please try again')\n", " \n", "vowel_dict\n"]}, {"cell_type": "code", "execution_count": null, "id": "a8a21a99", "metadata": {}, "outputs": [], "source": ["\n"]}, {"cell_type": "code", "execution_count": null, "id": "eacd8d5e", "metadata": {}, "outputs": [], "source": ["\n"]}, {"cell_type": "markdown", "id": "a25b6119", "metadata": {"slideshow": {"slide_type": "slide"}}, "source": ["# Other Useful For Loops\n", "\n", "- `enumerate`\n", " - allows us to iterate through index & item pairs\n", " - (helpful if you have a situation where you need both)\n", "- `zip`\n", " - allows us to iterate through two ordered variables together\n", " \n", "- ++ [there are others in \"itertools\" too](https://docs.python.org/3/library/itertools.html)\n", " - cartesian product\n", " - combination / permutation / combination with replacement\n"]}, {"cell_type": "code", "execution_count": 26, "id": "32d3297f", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["0 a\n", "1 b\n", "2 c\n", "3 d\n"]}], "source": ["# if you need an index too, use enumerate\n", "some_list = ['a', 'b', 'c', 'd']\n", "for idx, item in enumerate(some_list):\n", " print(idx, item)\n"]}, {"cell_type": "code", "execution_count": 27, "id": "28518e1a", "metadata": {}, "outputs": [{"name": "stdout", "output_type": "stream", "text": ["a q\n", "s w\n", "d e\n", "f r\n"]}], "source": ["# zip iterates through corresponding items in two ordered (e.g. lists/tuples/strings) types\n", "# the 1st time through the loop it gets the 1st items from each ...\n", "# the 2nd time through the loop it gets the 2nd items from each ...\n", "string0 = 'asdf'\n", "string1 = 'qwer'\n", "\n", "for c0, c1 in zip(string0, string1):\n", " print(c0, c1)\n"]}], "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.10.6"}}, "nbformat": 4, "nbformat_minor": 5}