Skip to content

Instantly share code, notes, and snippets.

@heri
Created March 31, 2020 15:41
Show Gist options
  • Save heri/bf3769fe6b1d843d42a85e0730df0dff to your computer and use it in GitHub Desktop.
Save heri/bf3769fe6b1d843d42a85e0730df0dff to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{"cells":[{"metadata":{},"cell_type":"markdown","source":"\n## About Jupyter cells\n\nWhen you are editing a cell in Jupyter notebook, you need to re-run the cell by pressing **`<Shift> + <Enter>`**. This will allow changes you made to be available to other cells.\n\nUse **`<Enter>`** to make new lines inside a cell you are editing.\n\n#### Code cells\n\nRe-running will execute any statements you have written. To edit an existing code cell, click on it.\n\n<hr>"},{"metadata":{},"cell_type":"markdown","source":"## Common operations\n\nNear the top of the https://try.jupyter.org page, Jupyter provides a row of menu options (`File`, `Edit`, `View`, `Insert`, ...) and a row of tool bar icons (disk, plus sign, scissors, 2 files, clipboard and file, up arrow, ...).\n\n#### Inserting and removing cells\n\n- Use the \"plus sign\" icon to insert a cell below the currently selected cell\n- Use \"Insert\" -> \"Insert Cell Above\" from the menu to insert above\n\n#### Save your notebook file locally\n\n- Clear the output of all cells\n- Use \"File\" -> \"Download as\" -> \"IPython Notebook (.ipynb)\" to download a notebook file representing your https://try.jupyter.org session\n\n<hr>"},{"metadata":{},"cell_type":"markdown","source":"## References\n\n- https://try.jupyter.org\n- https://docs.python.org/3/tutorial/index.html\n\n<hr>"},{"metadata":{},"cell_type":"markdown","source":"## Python objects, basic types, and variables\n\nEverything in Python is an **object** and every object in Python has a **type**. Some of the basic types include:\n\n- **`int`** (integer; a whole number with no decimal place)\n - `10`\n - `-3`\n- **`float`** (float; a number that has a decimal place)\n - `7.41`\n - `-0.006`\n- **`str`** (string; a sequence of characters enclosed in single quotes, double quotes, or triple quotes)\n - `'this is a string using single quotes'`\n - `\"this is a string using double quotes\"`\n - `'''this is a triple quoted string using single quotes'''`\n - `\"\"\"this is a triple quoted string using double quotes\"\"\"`\n- **`bool`** (boolean; a binary value that is either true or false)\n - `True`\n - `False`\n- **`NoneType`** (a special type representing the absence of a value)\n - `None`\n\nIn Python, a **variable** is a name you specify in your code that maps to a particular **object**, object **instance**, or value.\n\nBy defining variables, we can refer to things by names that make sense to us. Names for variables can only contain letters, underscores (`_`), or numbers (no spaces, dashes, or other characters). Variable names must start with a letter or underscore.\n\n<hr>"},{"metadata":{},"cell_type":"markdown","source":"## Basic operators\n\nIn Python, there are different types of **operators** (special symbols) that operate on different values. Some of the basic operators include:\n\n- arithmetic operators\n - **`+`** (addition)\n - **`-`** (subtraction)\n - **`*`** (multiplication)\n - **`/`** (division)\n - __`**`__ (exponent)\n- assignment operators\n - **`=`** (assign a value)\n - **`+=`** (add and re-assign; increment)\n - **`-=`** (subtract and re-assign; decrement)\n - **`*=`** (multiply and re-assign)\n- comparison operators (return either `True` or `False`)\n - **`==`** (equal to)\n - **`!=`** (not equal to)\n - **`<`** (less than)\n - **`<=`** (less than or equal to)\n - **`>`** (greater than)\n - **`>=`** (greater than or equal to)\n\nWhen multiple operators are used in a single expression, **operator precedence** determines which parts of the expression are evaluated in which order. Operators with higher precedence are evaluated first (like PEMDAS in math). Operators with the same precedence are evaluated from left to right.\n\n- `()` parentheses, for grouping\n- `**` exponent\n- `*`, `/` multiplication and division\n- `+`, `-` addition and subtraction\n- `==`, `!=`, `<`, `<=`, `>`, `>=` comparisons\n\n> See https://docs.python.org/3/reference/expressions.html#operator-precedence"},{"metadata":{"trusted":false},"cell_type":"code","source":"# Assigning some numbers to different variables\nnum1 = 10\nnum2 = -3\nnum3 = 7.41\nnum4 = -.6\nnum5 = 7\nnum6 = 3\nnum7 = 11.11","execution_count":2,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Addition\nnum1 + num2","execution_count":3,"outputs":[{"data":{"text/plain":"7"},"execution_count":3,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Subtraction\nnum2 - num3","execution_count":3,"outputs":[{"data":{"text/plain":"-10.41"},"execution_count":3,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Multiplication\nnum3 * num4","execution_count":4,"outputs":[{"data":{"text/plain":"-4.446"},"execution_count":4,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Division\nnum4 / num5","execution_count":5,"outputs":[{"data":{"text/plain":"-0.08571428571428572"},"execution_count":5,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Exponent\nnum5 ** num6","execution_count":6,"outputs":[{"data":{"text/plain":"343"},"execution_count":6,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Increment existing variable\nnum7 += 4\nnum7","execution_count":7,"outputs":[{"data":{"text/plain":"15.11"},"execution_count":7,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Decrement existing variable\nnum6 -= 2\nnum6","execution_count":8,"outputs":[{"data":{"text/plain":"1"},"execution_count":8,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Multiply & re-assign\nnum3 *= 5\nnum3","execution_count":9,"outputs":[{"data":{"text/plain":"37.05"},"execution_count":9,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Assign the value of an expression to a variable\nnum8 = num1 + num2 * num3\nnum8","execution_count":10,"outputs":[{"data":{"text/plain":"-101.14999999999999"},"execution_count":10,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Are these two expressions equal to each other?\nnum1 + num2 == num5","execution_count":11,"outputs":[{"data":{"text/plain":"True"},"execution_count":11,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Are these two expressions not equal to each other?\nnum3 != num4","execution_count":12,"outputs":[{"data":{"text/plain":"True"},"execution_count":12,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Is the first expression less than the second expression?\nnum5 < num6","execution_count":13,"outputs":[{"data":{"text/plain":"False"},"execution_count":13,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Is this expression True?\n5 > 3 > 1","execution_count":14,"outputs":[{"data":{"text/plain":"True"},"execution_count":14,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Is this expression True?\n5 > 3 < 4 == 3 + 1","execution_count":15,"outputs":[{"data":{"text/plain":"True"},"execution_count":15,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"# Assign some strings to different variables\nsimple_string1 = 'an example'\nsimple_string2 = \"oranges \"","execution_count":16,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Addition\nsimple_string1 + ' of using the + operator'","execution_count":17,"outputs":[{"data":{"text/plain":"'an example of using the + operator'"},"execution_count":17,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Notice that the string was not modified\nsimple_string1","execution_count":18,"outputs":[{"data":{"text/plain":"'an example'"},"execution_count":18,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Multiplication\nsimple_string2 * 4","execution_count":19,"outputs":[{"data":{"text/plain":"'oranges oranges oranges oranges '"},"execution_count":19,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# This string wasn't modified either\nsimple_string2","execution_count":20,"outputs":[{"data":{"text/plain":"'oranges '"},"execution_count":20,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Are these two expressions equal to each other?\nsimple_string1 == simple_string2","execution_count":21,"outputs":[{"data":{"text/plain":"False"},"execution_count":21,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Are these two expressions equal to each other?\nsimple_string1 == 'an example'","execution_count":22,"outputs":[{"data":{"text/plain":"True"},"execution_count":22,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Add and re-assign\nsimple_string1 += ' that re-assigned the original string'\nsimple_string1","execution_count":23,"outputs":[{"data":{"text/plain":"'an example that re-assigned the original string'"},"execution_count":23,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Multiply and re-assign\nsimple_string2 *= 3\nsimple_string2","execution_count":24,"outputs":[{"data":{"text/plain":"'oranges oranges oranges '"},"execution_count":24,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"# Note: Subtraction, division, and decrement operators do not apply to strings.","execution_count":25,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Basic containers\n\n> Note: **mutable** objects can be modified after creation and **immutable** objects cannot.\n\nContainers are objects that can be used to group other objects together. The basic container types include:\n\n- **`str`** (string: immutable; indexed by integers; items are stored in the order they were added)\n- **`list`** (list: mutable; indexed by integers; items are stored in the order they were added)\n - `[3, 5, 6, 3, 'dog', 'cat', False]`\n- **`tuple`** (tuple: immutable; indexed by integers; items are stored in the order they were added)\n - `(3, 5, 6, 3, 'dog', 'cat', False)`\n- **`set`** (set: mutable; not indexed at all; items are NOT stored in the order they were added; can only contain immutable objects; does NOT contain duplicate objects)\n - `{3, 5, 6, 3, 'dog', 'cat', False}`\n- **`dict`** (dictionary: mutable; key-value pairs are indexed by immutable keys; items are NOT stored in the order they were added)\n - `{'name': 'Jane', 'age': 23, 'fav_foods': ['pizza', 'fruit', 'fish']}`\n\nWhen defining lists, tuples, or sets, use commas (,) to separate the individual items. When defining dicts, use a colon (:) to separate keys from values and commas (,) to separate the key-value pairs.\n\nStrings, lists, and tuples are all **sequence types** that can use the `+`, `*`, `+=`, and `*=` operators."},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"# Assign some containers to different variables\nlist1 = [3, 5, 6, 3, 'dog', 'cat', False]\ntuple1 = (3, 5, 6, 3, 'dog', 'cat', False)\nset1 = {3, 5, 6, 3, 'dog', 'cat', False}\ndict1 = {'name': 'Jane', 'age': 23, 'fav_foods': ['pizza', 'fruit', 'fish']}","execution_count":26,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Items in the list object are stored in the order they were added\nlist1","execution_count":27,"outputs":[{"data":{"text/plain":"[3, 5, 6, 3, 'dog', 'cat', False]"},"execution_count":27,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Items in the tuple object are stored in the order they were added\ntuple1","execution_count":28,"outputs":[{"data":{"text/plain":"(3, 5, 6, 3, 'dog', 'cat', False)"},"execution_count":28,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Items in the set object are not stored in the order they were added\n# Also, notice that the value 3 only appears once in this set object\nset1","execution_count":29,"outputs":[{"data":{"text/plain":"{False, 3, 5, 6, 'dog', 'cat'}"},"execution_count":29,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Items in the dict object are not stored in the order they were added\ndict1","execution_count":30,"outputs":[{"data":{"text/plain":"{'age': 23, 'fav_foods': ['pizza', 'fruit', 'fish'], 'name': 'Jane'}"},"execution_count":30,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Add and re-assign\nlist1 += [5, 'grapes']\nlist1","execution_count":31,"outputs":[{"data":{"text/plain":"[3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes']"},"execution_count":31,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Add and re-assign\ntuple1 += (5, 'grapes')\ntuple1","execution_count":32,"outputs":[{"data":{"text/plain":"(3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes')"},"execution_count":32,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Multiply\n[1, 2, 3, 4] * 2","execution_count":33,"outputs":[{"data":{"text/plain":"[1, 2, 3, 4, 1, 2, 3, 4]"},"execution_count":33,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Multiply\n(1, 2, 3, 4) * 3","execution_count":34,"outputs":[{"data":{"text/plain":"(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)"},"execution_count":34,"metadata":{},"output_type":"execute_result"}]},{"metadata":{},"cell_type":"markdown","source":"## Accessing data in containers\n\nFor strings, lists, tuples, and dicts, we can use **subscript notation** (square brackets) to access data at an index.\n\n- strings, lists, and tuples are indexed by integers, **starting at 0** for first item\n - these sequence types also support accesing a range of items, known as **slicing**\n - use **negative indexing** to start at the back of the sequence\n- dicts are indexed by their keys\n\n> Note: sets are not indexed, so we cannot use subscript notation to access data elements."},{"metadata":{"trusted":false},"cell_type":"code","source":"# Access the first item in a sequence\nlist1[0]","execution_count":35,"outputs":[{"data":{"text/plain":"3"},"execution_count":35,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Access the last item in a sequence\ntuple1[-1]","execution_count":36,"outputs":[{"data":{"text/plain":"'grapes'"},"execution_count":36,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Access a range of items in a sequence\nsimple_string1[3:8]","execution_count":37,"outputs":[{"data":{"text/plain":"'examp'"},"execution_count":37,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Access a range of items in a sequence\ntuple1[:-3]","execution_count":38,"outputs":[{"data":{"text/plain":"(3, 5, 6, 3, 'dog', 'cat')"},"execution_count":38,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Access a range of items in a sequence\nlist1[4:]","execution_count":39,"outputs":[{"data":{"text/plain":"['dog', 'cat', False, 5, 'grapes']"},"execution_count":39,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Access an item in a dictionary\ndict1['name']","execution_count":40,"outputs":[{"data":{"text/plain":"'Jane'"},"execution_count":40,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Access an element of a sequence in a dictionary\ndict1['fav_foods'][2]","execution_count":41,"outputs":[{"data":{"text/plain":"'fish'"},"execution_count":41,"metadata":{},"output_type":"execute_result"}]},{"metadata":{},"cell_type":"markdown","source":"## Python built-in functions and callables\n\nA **function** is a Python object that you can \"call\" to **perform an action** or compute and **return another object**. You call a function by placing parentheses to the right of the function name. Some functions allow you to pass **arguments** inside the parentheses (separating multiple arguments with a comma). Internal to the function, these arguments are treated like variables.\n\nPython has several useful built-in functions to help you work with different objects and/or your environment. Here is a small sample of them:\n\n- **`type(obj)`** to determine the type of an object\n- **`len(container)`** to determine how many items are in a container\n- **`callable(obj)`** to determine if an object is callable\n- **`sorted(container)`** to return a new list from a container, with the items sorted\n- **`sum(container)`** to compute the sum of a container of numbers\n- **`min(container)`** to determine the smallest item in a container\n- **`max(container)`** to determine the largest item in a container\n- **`abs(number)`** to determine the absolute value of a number\n- **`repr(obj)`** to return a string representation of an object\n\n> Complete list of built-in functions: https://docs.python.org/3/library/functions.html\n\nThere are also different ways of defining your own functions and callable objects that we will explore later."},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the type() function to determine the type of an object\ntype(simple_string1)","execution_count":42,"outputs":[{"data":{"text/plain":"str"},"execution_count":42,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the len() function to determine how many items are in a container\nlen(dict1)","execution_count":43,"outputs":[{"data":{"text/plain":"3"},"execution_count":43,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the len() function to determine how many items are in a container\nlen(simple_string2)","execution_count":44,"outputs":[{"data":{"text/plain":"24"},"execution_count":44,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the callable() function to determine if an object is callable\ncallable(len)","execution_count":45,"outputs":[{"data":{"text/plain":"True"},"execution_count":45,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the callable() function to determine if an object is callable\ncallable(dict1)","execution_count":46,"outputs":[{"data":{"text/plain":"False"},"execution_count":46,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the sorted() function to return a new list from a container, with the items sorted\nsorted([10, 1, 3.6, 7, 5, 2, -3])","execution_count":47,"outputs":[{"data":{"text/plain":"[-3, 1, 2, 3.6, 5, 7, 10]"},"execution_count":47,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the sorted() function to return a new list from a container, with the items sorted\n# - notice that capitalized strings come first\nsorted(['dogs', 'cats', 'zebras', 'Chicago', 'California', 'ants', 'mice'])","execution_count":48,"outputs":[{"data":{"text/plain":"['California', 'Chicago', 'ants', 'cats', 'dogs', 'mice', 'zebras']"},"execution_count":48,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the sum() function to compute the sum of a container of numbers\nsum([10, 1, 3.6, 7, 5, 2, -3])","execution_count":49,"outputs":[{"data":{"text/plain":"25.6"},"execution_count":49,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the min() function to determine the smallest item in a container\nmin([10, 1, 3.6, 7, 5, 2, -3])","execution_count":50,"outputs":[{"data":{"text/plain":"-3"},"execution_count":50,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the min() function to determine the smallest item in a container\nmin(['g', 'z', 'a', 'y'])","execution_count":51,"outputs":[{"data":{"text/plain":"'a'"},"execution_count":51,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the max() function to determine the largest item in a container\nmax([10, 1, 3.6, 7, 5, 2, -3])","execution_count":52,"outputs":[{"data":{"text/plain":"10"},"execution_count":52,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the max() function to determine the largest item in a container\nmax('gibberish')","execution_count":53,"outputs":[{"data":{"text/plain":"'s'"},"execution_count":53,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the abs() function to determine the absolute value of a number\nabs(10)","execution_count":54,"outputs":[{"data":{"text/plain":"10"},"execution_count":54,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the abs() function to determine the absolute value of a number\nabs(-12)","execution_count":55,"outputs":[{"data":{"text/plain":"12"},"execution_count":55,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Use the repr() function to return a string representation of an object\nrepr(set1)","execution_count":56,"outputs":[{"data":{"text/plain":"\"{False, 3, 5, 6, 'dog', 'cat'}\""},"execution_count":56,"metadata":{},"output_type":"execute_result"}]},{"metadata":{},"cell_type":"markdown","source":"## Python object attributes (methods and properties)\n\nDifferent types of objects in Python have different **attributes** that can be referred to by name (similar to a variable). To access an attribute of an object, use a dot (`.`) after the object, then specify the attribute (i.e. `obj.attribute`)\n\nWhen an attribute of an object is a callable, that attribute is called a **method**. It is the same as a function, only this function is bound to a particular object.\n\nWhen an attribute of an object is not a callable, that attribute is called a **property**. It is just a piece of data about the object, that is itself another object.\n\nThe built-in `dir()` function can be used to return a list of an object's attributes.\n\n<hr>"},{"metadata":{},"cell_type":"markdown","source":"## Some methods on string objects\n\n- **`.capitalize()`** to return a capitalized version of the string (only first char uppercase)\n- **`.upper()`** to return an uppercase version of the string (all chars uppercase)\n- **`.lower()`** to return an lowercase version of the string (all chars lowercase)\n- **`.count(substring)`** to return the number of occurences of the substring in the string\n- **`.startswith(substring)`** to determine if the string starts with the substring\n- **`.endswith(substring)`** to determine if the string ends with the substring\n- **`.replace(old, new)`** to return a copy of the string with occurences of the \"old\" replaced by \"new\""},{"metadata":{"trusted":false},"cell_type":"code","source":"# Assign a string to a variable\na_string = 'tHis is a sTriNg'","execution_count":57,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Return a capitalized version of the string\na_string.capitalize()","execution_count":58,"outputs":[{"data":{"text/plain":"'This is a string'"},"execution_count":58,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Return an uppercase version of the string\na_string.upper()","execution_count":59,"outputs":[{"data":{"text/plain":"'THIS IS A STRING'"},"execution_count":59,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Return a lowercase version of the string\na_string.lower()","execution_count":60,"outputs":[{"data":{"text/plain":"'this is a string'"},"execution_count":60,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Notice that the methods called have not actually modified the string\na_string","execution_count":61,"outputs":[{"data":{"text/plain":"'tHis is a sTriNg'"},"execution_count":61,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Count number of occurences of a substring in the string\na_string.count('i')","execution_count":62,"outputs":[{"data":{"text/plain":"3"},"execution_count":62,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Count number of occurences of a substring in the string after a certain position\na_string.count('i', 7)","execution_count":63,"outputs":[{"data":{"text/plain":"1"},"execution_count":63,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Count number of occurences of a substring in the string\na_string.count('is')","execution_count":64,"outputs":[{"data":{"text/plain":"2"},"execution_count":64,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Does the string start with 'this'?\na_string.startswith('this')","execution_count":65,"outputs":[{"data":{"text/plain":"False"},"execution_count":65,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Does the lowercase string start with 'this'?\na_string.lower().startswith('this')","execution_count":66,"outputs":[{"data":{"text/plain":"True"},"execution_count":66,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Does the string end with 'Ng'?\na_string.endswith('Ng')","execution_count":67,"outputs":[{"data":{"text/plain":"True"},"execution_count":67,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Return a version of the string with a substring replaced with something else\na_string.replace('is', 'XYZ')","execution_count":68,"outputs":[{"data":{"text/plain":"'tHXYZ XYZ a sTriNg'"},"execution_count":68,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Return a version of the string with a substring replaced with something else\na_string.replace('i', '!')","execution_count":69,"outputs":[{"data":{"text/plain":"'tH!s !s a sTr!Ng'"},"execution_count":69,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Return a version of the string with the first 2 occurences a substring replaced with something else\na_string.replace('i', '!', 2)","execution_count":70,"outputs":[{"data":{"text/plain":"'tH!s !s a sTriNg'"},"execution_count":70,"metadata":{},"output_type":"execute_result"}]},{"metadata":{"collapsed":true},"cell_type":"markdown","source":"## Some methods on list objects\n\n- **`.append(item)`** to add a single item to the list\n- **`.extend([item1, item2, ...])`** to add multiple items to the list\n- **`.remove(item)`** to remove a single item from the list\n- **`.pop()`** to remove and return the item at the end of the list\n- **`.pop(index)`** to remove and return an item at an index"},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Some methods on set objects\n\n- **`.add(item)`** to add a single item to the set\n- **`.update([item1, item2, ...])`** to add multiple items to the set\n- **`.update(set2, set3, ...)`** to add items from all provided sets to the set\n- **`.remove(item)`** to remove a single item from the set\n- **`.pop()`** to remove and return a random item from the set\n- **`.difference(set2)`** to return items in the set that are not in another set\n- **`.intersection(set2)`** to return items in both sets\n- **`.union(set2)`** to return items that are in either set\n- **`.symmetric_difference(set2)`** to return items that are only in one set (not both)\n- **`.issuperset(set2)`** does the set contain everything in the other set?\n- **`.issubset(set2)`** is the set contained in the other set?"},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Some methods on dict objects\n\n- **`.update([(key1, val1), (key2, val2), ...])`** to add multiple key-value pairs to the dict\n- **`.update(dict2)`** to add all keys and values from another dict to the dict\n- **`.pop(key)`** to remove key and return its value from the dict (error if key not found)\n- **`.pop(key, default_val)`** to remove key and return its value from the dict (or return default_val if key not found)\n- **`.get(key)`** to return the value at a specified key in the dict (or None if key not found)\n- **`.get(key, default_val)`** to return the value at a specified key in the dict (or default_val if key not found)\n- **`.keys()`** to return a list of keys in the dict\n- **`.values()`** to return a list of values in the dict\n- **`.items()`** to return a list of key-value pairs (tuples) in the dict"},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Positional arguments and keyword arguments to callables\n\nYou can call a function/method in a number of different ways:\n\n- `func()`: Call `func` with no arguments\n- `func(arg)`: Call `func` with one positional argument\n- `func(arg1, arg2)`: Call `func` with two positional arguments\n- `func(arg1, arg2, ..., argn)`: Call `func` with many positional arguments\n- `func(kwarg=value)`: Call `func` with one keyword argument \n- `func(kwarg1=value1, kwarg2=value2)`: Call `func` with two keyword arguments\n- `func(kwarg1=value1, kwarg2=value2, ..., kwargn=valuen)`: Call `func` with many keyword arguments\n- `func(arg1, arg2, kwarg1=value1, kwarg2=value2)`: Call `func` with positonal arguments and keyword arguments\n- `obj.method()`: Same for `func`.. and every other `func` example\n\nWhen using **positional arguments**, you must provide them in the order that the function defined them (the function's **signature**).\n\nWhen using **keyword arguments**, you can provide the arguments you want, in any order you want, as long as you specify each argument's name.\n\nWhen using positional and keyword arguments, positional arguments must come first."},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Formatting strings and using placeholders"},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Python \"for loops\"\n\nIt is easy to **iterate** over a collection of items using a **for loop**. The strings, lists, tuples, sets, and dictionaries we defined are all **iterable** containers.\n\nThe for loop will go through the specified container, one item at a time, and provide a temporary variable for the current item. You can use this temporary variable like a normal variable."},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Python \"if statements\" and \"while loops\"\n\nConditional expressions can be used with these two **conditional statements**.\n\nThe **if statement** allows you to test a condition and perform some actions if the condition evaluates to `True`. You can also provide `elif` and/or `else` clauses to an if statement to take alternative actions if the condition evaluates to `False`.\n\nThe **while loop** will keep looping until its conditional expression evaluates to `False`.\n\n> Note: It is possible to \"loop forever\" when using a while loop with a conditional expression that never evaluates to `False`.\n>\n> Note: Since the **for loop** will iterate over a container of items until there are no more, there is no need to specify a \"stop looping\" condition."},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## List, set, and dict comprehensions"},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Creating objects from arguments or other objects\n\nThe basic types and containers we have used so far all provide **type constructors**:\n\n- `int()`\n- `float()`\n- `str()`\n- `list()`\n- `tuple()`\n- `set()`\n- `dict()`\n\nUp to this point, we have been defining objects of these built-in types using some syntactic shortcuts, since they are so common.\n\nSometimes, you will have an object of one type that you need to convert to another type. Use the **type constructor** for the type of object you want to have, and pass in the object you currently have."},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Importing modules"},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Exceptions"},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Classes: Creating your own objects"},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"# Define a new class called `Thing` that is derived from the base Python object\nclass Thing(object):\n my_property = 'I am a \"Thing\"'\n\n\n# Define a new class called `DictThing` that is derived from the `dict` type\nclass DictThing(dict):\n my_property = 'I am a \"DictThing\"'","execution_count":71,"outputs":[]},{"metadata":{"trusted":false},"cell_type":"code","source":"print(Thing)\nprint(type(Thing))\nprint(DictThing)\nprint(type(DictThing))\nprint(issubclass(DictThing, dict))\nprint(issubclass(DictThing, object))","execution_count":72,"outputs":[{"name":"stdout","output_type":"stream","text":"<class '__main__.Thing'>\n<class 'type'>\n<class '__main__.DictThing'>\n<class 'type'>\nTrue\nTrue\n"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Create \"instances\" of our new classes\nt = Thing()\nd = DictThing()\nprint(t)\nprint(type(t))\nprint(d)\nprint(type(d))","execution_count":73,"outputs":[{"name":"stdout","output_type":"stream","text":"<__main__.Thing object at 0x7f2170f3d240>\n<class '__main__.Thing'>\n{}\n<class '__main__.DictThing'>\n"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"# Interact with a DictThing instance just as you would a normal dictionary\nd['name'] = 'Sally'\nprint(d)","execution_count":74,"outputs":[{"name":"stdout","output_type":"stream","text":"{'name': 'Sally'}\n"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"d.update({\n 'age': 13,\n 'fav_foods': ['pizza', 'sushi', 'pad thai', 'waffles'],\n 'fav_color': 'green',\n })\nprint(d)","execution_count":75,"outputs":[{"name":"stdout","output_type":"stream","text":"{'fav_color': 'green', 'name': 'Sally', 'fav_foods': ['pizza', 'sushi', 'pad thai', 'waffles'], 'age': 13}\n"}]},{"metadata":{"trusted":false},"cell_type":"code","source":"print(d.my_property)","execution_count":76,"outputs":[{"name":"stdout","output_type":"stream","text":"I am a \"DictThing\"\n"}]},{"metadata":{},"cell_type":"markdown","source":"## Defining functions and methods"},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Creating an initializer method for your classes"},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Other \"magic methods\""},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Context managers and the \"with statement\""},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"collapsed":true,"trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.7.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment