Skip to content

Instantly share code, notes, and snippets.

@gwincr11
Forked from kenjyco/01-Learning-Python3.md
Created July 15, 2021 13:48
Show Gist options
  • Save gwincr11/241deeece30554f102942a8349a3e52e to your computer and use it in GitHub Desktop.
Save gwincr11/241deeece30554f102942a8349a3e52e to your computer and use it in GitHub Desktop.
Learn Python 3 with Jupyter Notebook

Learning Python 3

This gist provides the learning-python3.ipynb notebook file, which can be viewed and edited in a Jupyter Notebook server to learn Python 3.

Once you load the notebook file to your local jupyter server, you can edit any of the cells, add new cells, or delete cells. The code cells will let you type and execute Python code (since we are using the Python 3 kernel). The markdown cells will let you type notes with a simple syntax.

Loading this notebook in a browser

Click https://mybinder.org/v2/gist/kenjyco/69eeb503125035f21a9d/HEAD?filepath=learning-python3.ipynb to start an interactive notebook from this gist in the browser. No need to install anything locally! You just need wait for the Docker image to be built on their server, then the JupyterHub server will load the notebook in a live environment.

  • Once the notebook loads, select "Cell" from the top area of menu items, then select "Run All"
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"[learning-python3.ipynb]: https://gist.githubusercontent.com/kenjyco/69eeb503125035f21a9d/raw/learning-python3.ipynb\n",
"[my-binder]: https://mybinder.org/v2/gist/kenjyco/69eeb503125035f21a9d/HEAD?filepath=learning-python3.ipynb\n",
"\n",
"Right-click -> \"save link as\" [https://gist.githubusercontent.com/kenjyco/69eeb503125035f21a9d/raw/learning-python3.ipynb][learning-python3.ipynb] to get most up-to-date version of this notebook file.\n",
"Click -> [https://mybinder.org/v2/gist/kenjyco/69eeb503125035f21a9d/HEAD?filepath=learning-python3.ipynb][my-binder] to load this notebook in the browser via mybinder.org\n",
"\n",
"## Quick note about Jupyter cells\n",
"\n",
"When 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",
"\n",
"Use **`<Enter>`** to make new lines inside a cell you are editing.\n",
"\n",
"#### Code cells\n",
"\n",
"Re-running will execute any statements you have written. To edit any existing code cell, click on it.\n",
"\n",
"#### Markdown cells\n",
"\n",
"Re-running will render the markdown text. To edit an existing markdown cell, double-click on it.\n",
"\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Common Jupyter operations\n",
"\n",
"Near the top of the Jupyter notebook window, there are 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",
"#### Clear the output of all cells\n",
"\n",
"- Use \"Kernel\" -> \"Restart\" from the menu to restart the kernel\n",
" - click on \"clear all outputs & restart\" to have all the output cleared\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://mybinder.org session\n",
"\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## References\n",
"\n",
"- https://jupyter-notebook.readthedocs.io/en/latest/notebook.html\n",
"- https://mybinder.readthedocs.io/en/latest/introduction.html\n",
"- https://docs.python.org/3/tutorial/index.html\n",
"- https://docs.python.org/3/tutorial/introduction.html\n",
"- https://daringfireball.net/projects/markdown/syntax\n",
"\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Python objects, basic types, and variables\n",
"\n",
"Everything 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",
"\n",
"In Python, a **variable** is a name you specify in your code that maps to a particular **object**, object **instance**, or value.\n",
"\n",
"By 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>"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Basic operators\n",
"\n",
"In 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",
"\n",
"When 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"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"# Assigning some numbers to different variables\n",
"num1 = 10\n",
"num2 = -3\n",
"num3 = 7.41\n",
"num4 = -.6\n",
"num5 = 7\n",
"num6 = 3\n",
"num7 = 11.11"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"7"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Addition\n",
"num1 + num2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"-10.41"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Subtraction\n",
"num2 - num3"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"-4.446"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiplication\n",
"num3 * num4"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"-0.08571428571428572"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Division\n",
"num4 / num5"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"343"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Exponent\n",
"num5 ** num6"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"15.11"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Increment existing variable\n",
"num7 += 4\n",
"num7"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Decrement existing variable\n",
"num6 -= 2\n",
"num6"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"37.05"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiply & re-assign\n",
"num3 *= 5\n",
"num3"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"-101.14999999999999"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Assign the value of an expression to a variable\n",
"num8 = num1 + num2 * num3\n",
"num8"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Are these two expressions equal to each other?\n",
"num1 + num2 == num5"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Are these two expressions not equal to each other?\n",
"num3 != num4"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Is the first expression less than the second expression?\n",
"num5 < num6"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Is this expression True?\n",
"5 > 3 > 1"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Is this expression True?\n",
"5 > 3 < 4 == 3 + 1"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"# Assign some strings to different variables\n",
"simple_string1 = 'an example'\n",
"simple_string2 = \"oranges \""
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'an example of using the + operator'"
]
},
"execution_count": 17,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Addition\n",
"simple_string1 + ' of using the + operator'"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'an example'"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Notice that the string was not modified\n",
"simple_string1"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'oranges oranges oranges oranges '"
]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiplication\n",
"simple_string2 * 4"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'oranges '"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# This string wasn't modified either\n",
"simple_string2"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Are these two expressions equal to each other?\n",
"simple_string1 == simple_string2"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Are these two expressions equal to each other?\n",
"simple_string1 == 'an example'"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'an example that re-assigned the original string'"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Add and re-assign\n",
"simple_string1 += ' that re-assigned the original string'\n",
"simple_string1"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'oranges oranges oranges '"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiply and re-assign\n",
"simple_string2 *= 3\n",
"simple_string2"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"# Note: Subtraction, division, and decrement operators do not apply to strings."
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Basic containers\n",
"\n",
"> Note: **mutable** objects can be modified after creation and **immutable** objects cannot.\n",
"\n",
"Containers 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",
"\n",
"When 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",
"\n",
"Strings, lists, and tuples are all **sequence types** that can use the `+`, `*`, `+=`, and `*=` operators."
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"# Assign some containers to different variables\n",
"list1 = [3, 5, 6, 3, 'dog', 'cat', False]\n",
"tuple1 = (3, 5, 6, 3, 'dog', 'cat', False)\n",
"set1 = {3, 5, 6, 3, 'dog', 'cat', False}\n",
"dict1 = {'name': 'Jane', 'age': 23, 'fav_foods': ['pizza', 'fruit', 'fish']}"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"[3, 5, 6, 3, 'dog', 'cat', False]"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Items in the list object are stored in the order they were added\n",
"list1"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"(3, 5, 6, 3, 'dog', 'cat', False)"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Items in the tuple object are stored in the order they were added\n",
"tuple1"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"{False, 3, 5, 6, 'dog', 'cat'}"
]
},
"execution_count": 29,
"metadata": {},
"output_type": "execute_result"
}
],
"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\n",
"set1"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"{'age': 23, 'fav_foods': ['pizza', 'fruit', 'fish'], 'name': 'Jane'}"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Items in the dict object are not stored in the order they were added\n",
"dict1"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"[3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes']"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Add and re-assign\n",
"list1 += [5, 'grapes']\n",
"list1"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"(3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes')"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Add and re-assign\n",
"tuple1 += (5, 'grapes')\n",
"tuple1"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3, 4, 1, 2, 3, 4]"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiply\n",
"[1, 2, 3, 4] * 2"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiply\n",
"(1, 2, 3, 4) * 3"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Accessing data in containers\n",
"\n",
"For 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."
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Access the first item in a sequence\n",
"list1[0]"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'grapes'"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Access the last item in a sequence\n",
"tuple1[-1]"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'examp'"
]
},
"execution_count": 37,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Access a range of items in a sequence\n",
"simple_string1[3:8]"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"(3, 5, 6, 3, 'dog', 'cat')"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Access a range of items in a sequence\n",
"tuple1[:-3]"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"['dog', 'cat', False, 5, 'grapes']"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Access a range of items in a sequence\n",
"list1[4:]"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'Jane'"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Access an item in a dictionary\n",
"dict1['name']"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'fish'"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Access an element of a sequence in a dictionary\n",
"dict1['fav_foods'][2]"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Python built-in functions and callables\n",
"\n",
"A **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",
"\n",
"Python 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",
"\n",
"There are also different ways of defining your own functions and callable objects that we will explore later."
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"str"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the type() function to determine the type of an object\n",
"type(simple_string1)"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the len() function to determine how many items are in a container\n",
"len(dict1)"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"24"
]
},
"execution_count": 44,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the len() function to determine how many items are in a container\n",
"len(simple_string2)"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the callable() function to determine if an object is callable\n",
"callable(len)"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the callable() function to determine if an object is callable\n",
"callable(dict1)"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"[-3, 1, 2, 3.6, 5, 7, 10]"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the sorted() function to return a new list from a container, with the items sorted\n",
"sorted([10, 1, 3.6, 7, 5, 2, -3])"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"['California', 'Chicago', 'ants', 'cats', 'dogs', 'mice', 'zebras']"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the sorted() function to return a new list from a container, with the items sorted\n",
"# - notice that capitalized strings come first\n",
"sorted(['dogs', 'cats', 'zebras', 'Chicago', 'California', 'ants', 'mice'])"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"25.6"
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the sum() function to compute the sum of a container of numbers\n",
"sum([10, 1, 3.6, 7, 5, 2, -3])"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"-3"
]
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the min() function to determine the smallest item in a container\n",
"min([10, 1, 3.6, 7, 5, 2, -3])"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'a'"
]
},
"execution_count": 51,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the min() function to determine the smallest item in a container\n",
"min(['g', 'z', 'a', 'y'])"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"10"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the max() function to determine the largest item in a container\n",
"max([10, 1, 3.6, 7, 5, 2, -3])"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'s'"
]
},
"execution_count": 53,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the max() function to determine the largest item in a container\n",
"max('gibberish')"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"10"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the abs() function to determine the absolute value of a number\n",
"abs(10)"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"12"
]
},
"execution_count": 55,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the abs() function to determine the absolute value of a number\n",
"abs(-12)"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"\"{False, 3, 5, 6, 'dog', 'cat'}\""
]
},
"execution_count": 56,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Use the repr() function to return a string representation of an object\n",
"repr(set1)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Python object attributes (methods and properties)\n",
"\n",
"Different 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",
"\n",
"When 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",
"\n",
"When 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",
"\n",
"The built-in `dir()` function can be used to return a list of an object's attributes.\n",
"\n",
"<hr>"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"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\""
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"# Assign a string to a variable\n",
"a_string = 'tHis is a sTriNg'"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'This is a string'"
]
},
"execution_count": 58,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Return a capitalized version of the string\n",
"a_string.capitalize()"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'THIS IS A STRING'"
]
},
"execution_count": 59,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Return an uppercase version of the string\n",
"a_string.upper()"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'this is a string'"
]
},
"execution_count": 60,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Return a lowercase version of the string\n",
"a_string.lower()"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'tHis is a sTriNg'"
]
},
"execution_count": 61,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Notice that the methods called have not actually modified the string\n",
"a_string"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 62,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Count number of occurences of a substring in the string\n",
"a_string.count('i')"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Count number of occurences of a substring in the string after a certain position\n",
"a_string.count('i', 7)"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 64,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Count number of occurences of a substring in the string\n",
"a_string.count('is')"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 65,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Does the string start with 'this'?\n",
"a_string.startswith('this')"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 66,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Does the lowercase string start with 'this'?\n",
"a_string.lower().startswith('this')"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 67,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Does the string end with 'Ng'?\n",
"a_string.endswith('Ng')"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'tHXYZ XYZ a sTriNg'"
]
},
"execution_count": 68,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Return a version of the string with a substring replaced with something else\n",
"a_string.replace('is', 'XYZ')"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'tH!s !s a sTr!Ng'"
]
},
"execution_count": 69,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Return a version of the string with a substring replaced with something else\n",
"a_string.replace('i', '!')"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"data": {
"text/plain": [
"'tH!s !s a sTriNg'"
]
},
"execution_count": 70,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Return a version of the string with the first 2 occurences a substring replaced with something else\n",
"a_string.replace('i', '!', 2)"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"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"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"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?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"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"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Positional arguments and keyword arguments to callables\n",
"\n",
"You 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",
"\n",
"When using **positional arguments**, you must provide them in the order that the function defined them (the function's **signature**).\n",
"\n",
"When 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",
"\n",
"When using positional and keyword arguments, positional arguments must come first."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Formatting strings and using placeholders"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Python \"for loops\"\n",
"\n",
"It 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",
"\n",
"The 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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Python \"if statements\" and \"while loops\"\n",
"\n",
"Conditional expressions can be used with these two **conditional statements**.\n",
"\n",
"The **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",
"\n",
"The **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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## List, set, and dict comprehensions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Creating objects from arguments or other objects\n",
"\n",
"The 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",
"\n",
"Up to this point, we have been defining objects of these built-in types using some syntactic shortcuts, since they are so common.\n",
"\n",
"Sometimes, 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."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Importing modules"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Exceptions"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Classes: Creating your own objects"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": [
"# Define a new class called `Thing` that is derived from the base Python object\n",
"class 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\n",
"class DictThing(dict):\n",
" my_property = 'I am a \"DictThing\"'"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class '__main__.Thing'>\n",
"<class 'type'>\n",
"<class '__main__.DictThing'>\n",
"<class 'type'>\n",
"True\n",
"True\n"
]
}
],
"source": [
"print(Thing)\n",
"print(type(Thing))\n",
"print(DictThing)\n",
"print(type(DictThing))\n",
"print(issubclass(DictThing, dict))\n",
"print(issubclass(DictThing, object))"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<__main__.Thing object at 0x7f2170f3d240>\n",
"<class '__main__.Thing'>\n",
"{}\n",
"<class '__main__.DictThing'>\n"
]
}
],
"source": [
"# Create \"instances\" of our new classes\n",
"t = Thing()\n",
"d = DictThing()\n",
"print(t)\n",
"print(type(t))\n",
"print(d)\n",
"print(type(d))"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'name': 'Sally'}\n"
]
}
],
"source": [
"# Interact with a DictThing instance just as you would a normal dictionary\n",
"d['name'] = 'Sally'\n",
"print(d)"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'fav_color': 'green', 'name': 'Sally', 'fav_foods': ['pizza', 'sushi', 'pad thai', 'waffles'], 'age': 13}\n"
]
}
],
"source": [
"d.update({\n",
" 'age': 13,\n",
" 'fav_foods': ['pizza', 'sushi', 'pad thai', 'waffles'],\n",
" 'fav_color': 'green',\n",
" })\n",
"print(d)"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {
"collapsed": false,
"deletable": true,
"editable": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I am a \"DictThing\"\n"
]
}
],
"source": [
"print(d.my_property)"
]
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Defining functions and methods"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Creating an initializer method for your classes"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Other \"magic methods\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"deletable": true,
"editable": true
},
"source": [
"## Context managers and the \"with statement\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"deletable": true,
"editable": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
The MIT License (MIT)
Copyright (c) 2019 Ken
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment