{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Getting The Python Basics Right\n", "\n", "Special thanks to PyQuantNews for donating this content. Subscribe [here](https://www.pyquantnews.com/) for free Python resources that will help you get started with Python for Quant Finance.\n", "\n", "## Code Comments\n", "\n", "A comment is a note made by a programmer in the source code of a program. Its purpose is to clarify the source code and make it easier for people to follow along with what is happening. Anything in a comment is generally ignored when the code is actually run, making comments useful for including explanations and reasoning as well as removing specific lines of code that you may be unsure about. Comments in Python are created by using the pound symbol (`# Insert Text Here`). Including a `#` in a line of code will comment out anything that follows it." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "# This is a comment\n", "# These lines of code will not change any values\n", "# Anything following the first # is not run as code" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You may hear text enclosed in triple quotes (`\"\"\" Insert Text Here \"\"\"`) referred to as multi-line comments, but this is not entirely accurate. This is a special type of `string` (a data type we will cover), called a `docstring`, used to explain the purpose of a function." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "' This is a special string '" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"\"\" This is a special string \"\"\"" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\u001b[0;31mInit signature:\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m/\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m*\u001b[0m\u001b[0margs\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m**\u001b[0m\u001b[0mkwargs\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mDocstring:\u001b[0m \n", "str(object='') -> str\n", "str(bytes_or_buffer[, encoding[, errors]]) -> str\n", "\n", "Create a new string object from the given object. If encoding or\n", "errors is specified, then the object must expose a data buffer\n", "that will be decoded using the given encoding and error handler.\n", "Otherwise, returns the result of object.__str__() (if defined)\n", "or repr(object).\n", "encoding defaults to sys.getdefaultencoding().\n", "errors defaults to 'strict'.\n", "\u001b[0;31mType:\u001b[0m type\n", "\u001b[0;31mSubclasses:\u001b[0m StrEnum, DeferredConfigString, FoldedCase, _rstr, _ScriptTarget, _ModuleTarget, LSString, include, Keys, InputMode, ..." ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "str??" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Make sure you read the comments within each code cell (if they are there). They will provide more real-time explanations of what is going on as you look at each line of code." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python Objects - Basic Types & 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", "
" ] }, { "cell_type": "markdown", "metadata": {}, "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": 4, "metadata": {}, "outputs": [], "source": [ "# Assigning some numbers to different variables\n", "num_1 = 10\n", "num_2 = -3\n", "num_3 = 7.41\n", "num_4 = -0.6\n", "num_5 = 7\n", "num_6 = 3\n", "num_7 = 11.11" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "num_1" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Addition\n", "num_1 + num_2" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-10.41" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Subtraction\n", "num_2 - num_3" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-4.446" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Multiplication\n", "num_3 * num_4" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-0.08571428571428572" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Division\n", "num_4 / num_5" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "343" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Exponent\n", "num_5**num_6" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "15.11" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Increment existing variable\n", "num_7 += 4 # num_7 = num_7 + 4\n", "num_7" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Decrement existing variable\n", "num_6 -= 2\n", "num_6" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "37.05" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Multiply & re-assign\n", "num_3 *= 5\n", "num_3" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-101.14999999999999" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Assign the value of an expression to a variable\n", "num_8 = num_1 + num_2 * num_3\n", "num_8" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Are these two expressions equal to each other?\n", "num_1 + num_2 == num_5" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Are these two expressions not equal to each other?\n", "num_3 != num_4" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Is the first expression less than the second expression?\n", "num_5 < num_6" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Is this expression True?\n", "5 > 3 > 1" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Is this expression True?\n", "5 > 3 < 4 == 3 + 1" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "# Assign some strings to different variables\n", "simple_string_1 = \"an example\"\n", "simple_string_2 = \"oranges \"" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'an example of using the + operator'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Addition\n", "simple_string_1 + \" of using the + operator\"" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'an example'" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Notice that the string was not modified\n", "simple_string_1" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'oranges oranges oranges oranges '" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Multiplication\n", "simple_string_2 * 4" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'oranges '" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# This string wasn't modified either\n", "simple_string_2" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Are these two expressions equal to each other?\n", "simple_string_1 == simple_string_2" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Are these two expressions equal to each other?\n", "simple_string_1 == \"an example\"" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'an example that re-assigned the original string'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Add and re-assign\n", "simple_string_1 += \" that re-assigned the original string\"\n", "simple_string_1" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'oranges oranges oranges '" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Multiply and re-assign\n", "simple_string_2 *= 3\n", "simple_string_2" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "# Note: Subtraction, division, and decrement operators do not apply to strings." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic Data Structures\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": 30, "metadata": {}, "outputs": [], "source": [ "# Assign some containers to different variables\n", "list_1 = [3, 5, 6, 3, \"dog\", \"cat\", False]\n", "tuple_1 = (3, 5, 6, 3, \"dog\", \"cat\", False)\n", "set_1 = {3, 5, 6, 3, \"dog\", \"cat\", False}\n", "set_2 = set((\"jane\", \"jaya\", \"jukes\", \"jason\", \"john\"))\n", "dict_1 = {\"name\": \"Jane\", \"age\": 23, \"fav_foods\": [\"pizza\", \"fruit\", \"fish\"]}\n", "dict_2 = {\"name\": \"Javier\", \"age\": 45, \"fav_foods\": [\"chicken\", \"veg\", \"candy\"]}" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 5, 6, 3, 'dog', 'cat', False]" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Items in the list object are stored in the order they were added\n", "list_1" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(3, 5, 6, 3, 'dog', 'cat', False)" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Items in the tuple object are stored in the order they were added\n", "tuple_1" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{3, 5, 6, False, 'cat', 'dog'}" ] }, "execution_count": 33, "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", "set_1" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'name': 'Jane', 'age': 23, 'fav_foods': ['pizza', 'fruit', 'fish']}" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Items in the dict object are not stored in the order they were added\n", "dict_1" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes']" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Add and re-assign\n", "list_1 += [5, \"grapes\"]\n", "list_1" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes')" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Add and re-assign\n", "tuple_1 += (5, \"grapes\")\n", "tuple_1" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 1, 2, 3, 4]" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Multiply\n", "[1, 2, 3, 4] * 2" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Multiply\n", "(1, 2, 3, 4) * 3" ] }, { "cell_type": "markdown", "metadata": {}, "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": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes']" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Remember what's in list_1\n", "list_1" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Access the first item in a sequence\n", "list_1[0]" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes')" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Remember what's in tuple_1\n", "tuple_1" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'grapes'" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Access the last item in a sequence\n", "tuple_1[-1]" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'an example that re-assigned the original string'" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Access a range of items in a sequence\n", "simple_string_1" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'n'" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "simple_string_1[1]" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'an ex'" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "simple_string_1[0:5]" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(5, 'grapes')" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Access a range of items in a sequence\n", "tuple_1[-2:]" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['dog', 'cat', False, 5, 'grapes']" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Access a range of items in a sequence\n", "list_1[4:]" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'name': 'Jane', 'age': 23, 'fav_foods': ['pizza', 'fruit', 'fish']}" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Rembember what's in dict_1\n", "dict_1" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Jane'" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Access an item in a dictionary\n", "# {'name': 'Jane', 'age': 23, 'fav_foods': ['pizza', 'fruit', 'fish']}\n", "dict_1[\"name\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python Built-In Functions & 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", "- **`isinstance(val, obj)`** to determine if `val` is an `obj`\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": 50, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 50, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use the type() function to determine the type of an object\n", "type(1.0)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "price = \"1.11\"\n", "isinstance(price, float)" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use the len() function to determine how many items are in a container\n", "len([1, 2, 3])" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "24" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use the len() function to determine how many items are in a container\n", "len(simple_string_2)" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use the callable() function to determine if an object is callable\n", "callable(\"a\")" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use the callable() function to determine if an object is callable\n", "callable(dict_1)" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[-3, 1, 2, 3.6, 5, 7, 10]" ] }, "execution_count": 56, "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": 57, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'j', 'n', 'o', 's']" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(\"jason\")" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['California', 'Chicago', 'ants', 'cats', 'dogs', 'mice', 'zebras']" ] }, "execution_count": 58, "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": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "25.6" ] }, "execution_count": 59, "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": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-3" ] }, "execution_count": 60, "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": 61, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'a'" ] }, "execution_count": 61, "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": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 62, "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": 63, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'s'" ] }, "execution_count": 63, "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": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 64, "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": 65, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 65, "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": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use the repr() function to return a string representation of an object\n", "isinstance(repr(list_1), str)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python Object Attributes (Methods & 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", "
" ] }, { "cell_type": "markdown", "metadata": {}, "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": 67, "metadata": {}, "outputs": [], "source": [ "# Assign a string to a variable\n", "a_string = \"tHis is a sTriNg\"" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'This is a string'" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return a capitalized version of the string\n", "a_string.capitalize()" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'THIS IS A STRING'" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return an uppercase version of the string\n", "a_string.upper()" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'this is a string'" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Return a lowercase version of the string\n", "a_string.lower()" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'tHis is a sTriNg'" ] }, "execution_count": 71, "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": 72, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 72, "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": 73, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 73, "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": 74, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 74, "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": 75, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Does the string start with 'this'?\n", "a_string.startswith(\"this\")" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Does the lowercase string start with 'this'?\n", "a_string.lower().startswith(\"this\")" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Does the string end with 'Ng'?\n", "a_string.endswith(\"Ng\")" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'tHXYZ XYZ a sTriNg'" ] }, "execution_count": 78, "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": 79, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'tH!s !s a sTr!Ng'" ] }, "execution_count": 79, "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": 80, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'tH!s !s a sTriNg'" ] }, "execution_count": 80, "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, "jupyter": { "outputs_hidden": 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": 81, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes']" ] }, "execution_count": 81, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Remember what's in list_1\n", "list_1" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes', 'basketball']" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# append a string to a list\n", "list_1.append(\"basketball\")\n", "list_1" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 5, 6, 3, 'dog', 'cat', False, 5, 'grapes', 'basketball', 'baseball', 1]" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Add multiple items to a list\n", "list_1.extend([\"baseball\", 1]) # equiv. list + list\n", "list_1" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 5, 6, 3, 'dog', False, 5, 'grapes', 'basketball', 'baseball', 1]" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Remove a sinle item from a list\n", "list_1.remove(\"cat\")\n", "list_1" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Remove the last item and return it\n", "list_1.pop()" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[3, 5, 6, 3, 'dog', False, 5, 'grapes', 'basketball', 'baseball']" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list_1" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 87, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# remove an item at index 0 and return it\n", "list_1.pop(0)" ] }, { "cell_type": "markdown", "metadata": {}, "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(set_2, set3, ...)`** to add items from all provided sets to the set\n", "- **`.remove(item)`** to remove a single item from the set\n", "- **`.difference(set_2)`** to return items in the set that are not in another set\n", "- **`.intersection(set_2)`** to return items in both sets\n", "- **`.union(set_2)`** to return items that are in either set\n", "- **`.symmetric_difference(set_2)`** to return items that are only in one set (not both)\n", "- **`.issuperset(set_2)`** does the set contain everything in the other set?\n", "- **`.issubset(set_2)`** is the set contained in the other set?" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Jason', 'jason'}" ] }, "execution_count": 88, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set([\"Jason\", \"jason\", \"jason\"])" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{3, 5, 6, False, 'cat', 'dog', 'fuzz'}" ] }, "execution_count": 89, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set_1.add(\"fuzz\")\n", "set_1" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{3, 5, 6, False, 'cat', 'coke', 'dog', 'fuzz', 'pepsi'}" ] }, "execution_count": 90, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set_1.update([\"coke\", \"pepsi\"])\n", "set_1" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{3,\n", " 5,\n", " 6,\n", " False,\n", " 'cat',\n", " 'coke',\n", " 'dog',\n", " 'fuzz',\n", " 'jane',\n", " 'jason',\n", " 'jaya',\n", " 'john',\n", " 'jukes',\n", " 'pepsi'}" ] }, "execution_count": 91, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set_1.update(set_2)\n", "set_1" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{3,\n", " 5,\n", " 6,\n", " False,\n", " 'coke',\n", " 'dog',\n", " 'fuzz',\n", " 'jane',\n", " 'jason',\n", " 'jaya',\n", " 'john',\n", " 'jukes',\n", " 'pepsi'}" ] }, "execution_count": 92, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set_1.remove(\"cat\")\n", "set_1" ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{3, 5, 6, False, 'coke', 'dog', 'fuzz', 'pepsi'}" ] }, "execution_count": 93, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set_1.difference(set_2)" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'jane', 'jason', 'jaya', 'john', 'jukes'}" ] }, "execution_count": 94, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set_1.intersection(set_2)" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{3,\n", " 5,\n", " 6,\n", " False,\n", " 'coke',\n", " 'dog',\n", " 'fuzz',\n", " 'jane',\n", " 'jason',\n", " 'jaya',\n", " 'john',\n", " 'jukes',\n", " 'pepsi'}" ] }, "execution_count": 95, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set_1.union(set_2)" ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 96, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set_1.issuperset(set_2)" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set_1.issubset(set_2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Some Methods On `dict` Objects\n", "\n", "- **`.update([(key1, val1), (key2, val2), ...])`** to add multiple key-value pairs to the dict\n", "- **`.update(dict_2)`** 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": 98, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'name': 'Jane', 'age': 23, 'fav_foods': ['pizza', 'fruit', 'fish']}" ] }, "execution_count": 98, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Remember what's in dict_1\n", "dict_1" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'name': 'Jane',\n", " 'age': 23,\n", " 'fav_foods': ['pizza', 'fruit', 'fish'],\n", " 'rain': True,\n", " 'cars': 'a lot'}" ] }, "execution_count": 99, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Update dict_1 with an iterable\n", "dict_1.update([(\"rain\", True), (\"cars\", \"a lot\")])\n", "dict_1" ] }, { "cell_type": "code", "execution_count": 100, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'name': 'Javier',\n", " 'age': 45,\n", " 'fav_foods': ['chicken', 'veg', 'candy'],\n", " 'rain': True,\n", " 'cars': 'a lot'}" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Update dict_1 with another dict\n", "dict_1.update(dict_2)\n", "dict_1" ] }, { "cell_type": "code", "execution_count": 101, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "45" ] }, "execution_count": 101, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Remove the key and value at age\n", "dict_1.pop(\"age\")" ] }, { "cell_type": "code", "execution_count": 102, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'name': 'Javier',\n", " 'fav_foods': ['chicken', 'veg', 'candy'],\n", " 'rain': True,\n", " 'cars': 'a lot'}" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Key and value are removed\n", "dict_1" ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "50" ] }, "execution_count": 103, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use a default value\n", "dict_1.pop(\"age\", 50)" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'No car found'" ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Use get to set a default\n", "dict_1.get(\"car\", \"No car found\")" ] }, { "cell_type": "code", "execution_count": 105, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_keys(['name', 'fav_foods', 'rain', 'cars'])" ] }, "execution_count": 105, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get the keys of a dict as an iterable\n", "dict_1.keys()" ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_values(['Javier', ['chicken', 'veg', 'candy'], True, 'a lot'])" ] }, "execution_count": 106, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get the values of a dict as an iterable\n", "dict_1.values()" ] }, { "cell_type": "code", "execution_count": 107, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_items([('name', 'Javier'), ('fav_foods', ['chicken', 'veg', 'candy']), ('rain', True), ('cars', 'a lot')])" ] }, "execution_count": 107, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Get the key-value pairs of a dict as an iterable\n", "dict_1.items()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Positional Arguments & 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": 108, "metadata": {}, "outputs": [], "source": [ "def func_1():\n", " return 1 + 1" ] }, { "cell_type": "code", "execution_count": 109, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 109, "metadata": {}, "output_type": "execute_result" } ], "source": [ "func_1()" ] }, { "cell_type": "code", "execution_count": 110, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "25" ] }, "execution_count": 110, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def func_2(x):\n", " return x**2 # equiv. x^2\n", "\n", "\n", "func_2(5)" ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4.0" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def func_3(x, y):\n", " return x / y\n", "\n", "\n", "func_3(8, 2)" ] }, { "cell_type": "code", "execution_count": 112, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'one': 1, 'two': 2, 'jason': 'banana'}\n" ] } ], "source": [ "def func_4(**kwargs):\n", " print(kwargs)\n", "\n", "\n", "func_4(one=1, two=2, jason=\"banana\")" ] }, { "cell_type": "code", "execution_count": 113, "metadata": {}, "outputs": [], "source": [ "def func_5(a, b, c, **kwargs):\n", " pass\n", "\n", "\n", "func_5(2, 3, c=5)" ] }, { "cell_type": "markdown", "metadata": {}, "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": 114, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "6\n", "3\n", "dog\n", "False\n", "5\n", "grapes\n", "basketball\n", "baseball\n" ] } ], "source": [ "list_1\n", "\n", "for item in list_1:\n", " print(item)" ] }, { "cell_type": "code", "execution_count": 115, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "5\n", "6\n", "3\n", "dog\n", "cat\n", "False\n", "5\n", "grapes\n" ] } ], "source": [ "for item in tuple_1:\n", " print(item)" ] }, { "cell_type": "code", "execution_count": 116, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "3\n", "5\n", "6\n", "john\n", "jane\n", "coke\n", "jukes\n", "jaya\n", "jason\n", "fuzz\n", "pepsi\n", "dog\n" ] } ], "source": [ "for item in set_1:\n", " print(item)" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Key:name -> Value:Javier\n", "Key:fav_foods -> Value:['chicken', 'veg', 'candy']\n", "Key:rain -> Value:True\n", "Key:cars -> Value:a lot\n" ] } ], "source": [ "for key, value in dict_1.items():\n", " print(f\"Key:{key} -> Value:{value}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python \"if statements\" & \"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": 118, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Correct\n" ] } ], "source": [ "if 1 < 2:\n", " print(\"Correct\")" ] }, { "cell_type": "code", "execution_count": 119, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 119, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 < 2" ] }, { "cell_type": "code", "execution_count": 120, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Correct\n" ] } ], "source": [ "if (1 < 2) and isinstance(\"jason\", str) and 1 and 12 < 20:\n", " print(\"Correct\")" ] }, { "cell_type": "code", "execution_count": 121, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Default\n" ] } ], "source": [ "if 1 > 2:\n", " print(\"Incorrect\")\n", "elif 1 > 3:\n", " print(\"Still incorrect\")\n", "else:\n", " print(\"Default\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## List Comprehensions" ] }, { "cell_type": "code", "execution_count": 122, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5]" ] }, "execution_count": 122, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create a simple list\n", "l = [1, 2, 3, 4, 5]\n", "l" ] }, { "cell_type": "code", "execution_count": 123, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]" ] }, "execution_count": 123, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# This does not multiply each value by 2\n", "l * 2" ] }, { "cell_type": "code", "execution_count": 124, "metadata": {}, "outputs": [], "source": [ "# The long way to do it...\n", "new_list = []\n", "for item in l:\n", " v = item * 2\n", " new_list.append(v)" ] }, { "cell_type": "code", "execution_count": 125, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 4, 6, 8, 10]" ] }, "execution_count": 125, "metadata": {}, "output_type": "execute_result" } ], "source": [ "new_list" ] }, { "cell_type": "code", "execution_count": 126, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 4, 6, 8, 10]" ] }, "execution_count": 126, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Same result using a list comprehension\n", "[item * 2 for item in l]" ] }, { "cell_type": "code", "execution_count": 127, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0.5, 1.0, 1.5, 2.0, 2.5]" ] }, "execution_count": 127, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Another example\n", "x = []\n", "for i in [1, 2, 3, 4, 5]:\n", " x.append(i / 2)\n", "x" ] }, { "cell_type": "code", "execution_count": 128, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[0.5, 1.0, 1.5, 2.0, 2.5]" ] }, "execution_count": 128, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[i / 2 for i in [1, 2, 3, 4, 5]]" ] }, { "cell_type": "code", "execution_count": 129, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[int, int, int, str, bool, int, str, str, str]" ] }, "execution_count": 129, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[type(i) for i in list_1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Importing Modules" ] }, { "cell_type": "code", "execution_count": 130, "metadata": {}, "outputs": [], "source": [ "import math\n", "import numpy" ] }, { "cell_type": "code", "execution_count": 131, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.0" ] }, "execution_count": 131, "metadata": {}, "output_type": "execute_result" } ], "source": [ "math.sqrt(9)" ] }, { "cell_type": "code", "execution_count": 132, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.0" ] }, "execution_count": 132, "metadata": {}, "output_type": "execute_result" } ], "source": [ "numpy.sqrt(9)" ] }, { "cell_type": "code", "execution_count": 133, "metadata": {}, "outputs": [], "source": [ "import math as m" ] }, { "cell_type": "code", "execution_count": 134, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.0" ] }, "execution_count": 134, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m.sqrt(9)" ] }, { "cell_type": "code", "execution_count": 135, "metadata": {}, "outputs": [], "source": [ "from math import sqrt\n", "from numpy import sqrt" ] }, { "cell_type": "code", "execution_count": 136, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.0" ] }, "execution_count": 136, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sqrt(9)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exceptions" ] }, { "cell_type": "code", "execution_count": 137, "metadata": {}, "outputs": [ { "ename": "KeyError", "evalue": "'food'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mKeyError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[137], line 2\u001b[0m\n\u001b[1;32m 1\u001b[0m dict3 \u001b[38;5;241m=\u001b[39m {\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mname\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mjason\u001b[39m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mcar\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mnope\u001b[39m\u001b[38;5;124m\"\u001b[39m}\n\u001b[0;32m----> 2\u001b[0m \u001b[43mdict3\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mfood\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\n", "\u001b[0;31mKeyError\u001b[0m: 'food'" ] } ], "source": [ "dict3 = {\"name\": \"jason\", \"car\": \"nope\"}\n", "dict3[\"food\"]" ] }, { "cell_type": "code", "execution_count": 138, "metadata": {}, "outputs": [ { "ename": "ZeroDivisionError", "evalue": "division by zero", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[138], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;241;43m2\u001b[39;49m\u001b[43m \u001b[49m\u001b[38;5;241;43m/\u001b[39;49m\u001b[43m \u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\n", "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero" ] } ], "source": [ "2 / 0" ] }, { "cell_type": "code", "execution_count": 139, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "set expected at most 1 argument, got 3", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[139], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28;43mset\u001b[39;49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m2\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m)\u001b[49m\n", "\u001b[0;31mTypeError\u001b[0m: set expected at most 1 argument, got 3" ] } ], "source": [ "set(1, 2, 3)" ] }, { "cell_type": "code", "execution_count": 140, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'jason' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[140], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mjason\u001b[49m\n", "\u001b[0;31mNameError\u001b[0m: name 'jason' is not defined" ] } ], "source": [ "jason" ] }, { "cell_type": "code", "execution_count": 141, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (1125386000.py, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m Cell \u001b[0;32mIn[141], line 1\u001b[0;36m\u001b[0m\n\u001b[0;31m 1 + 2:\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "1 + 2:" ] }, { "cell_type": "code", "execution_count": 150, "metadata": {}, "outputs": [ { "ename": "Exception", "evalue": "My own exception", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[150], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m(\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mMy own exception\u001b[39m\u001b[38;5;124m\"\u001b[39m)\n", "\u001b[0;31mException\u001b[0m: My own exception" ] } ], "source": [ "raise Exception(\"My own exception\")" ] }, { "cell_type": "code", "execution_count": 151, "metadata": {}, "outputs": [ { "ename": "AssertionError", "evalue": "Pass a number >=0", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[151], line 6\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m x \u001b[38;5;241m>\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m0\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mPass a number >=0\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m math\u001b[38;5;241m.\u001b[39msqrt(x)\n\u001b[0;32m----> 6\u001b[0m \u001b[43mfcn\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m-\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m)\u001b[49m\n", "Cell \u001b[0;32mIn[151], line 2\u001b[0m, in \u001b[0;36mfcn\u001b[0;34m(x)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mfcn\u001b[39m(x):\n\u001b[0;32m----> 2\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m x \u001b[38;5;241m>\u001b[39m\u001b[38;5;241m=\u001b[39m \u001b[38;5;241m0\u001b[39m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mPass a number >=0\u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 3\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m math\u001b[38;5;241m.\u001b[39msqrt(x)\n", "\u001b[0;31mAssertionError\u001b[0m: Pass a number >=0" ] } ], "source": [ "def fcn(x):\n", " assert x >= 0, \"Pass a number >=0\"\n", " return math.sqrt(x)\n", "\n", "\n", "fcn(-1)" ] }, { "cell_type": "code", "execution_count": 152, "metadata": {}, "outputs": [ { "ename": "ModuleNotFoundError", "evalue": "No module named 'my_module'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[152], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mmy_module\u001b[39;00m\n", "\u001b[0;31mModuleNotFoundError\u001b[0m: No module named 'my_module'" ] } ], "source": [ "import my_module" ] }, { "cell_type": "code", "execution_count": 153, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'calculate' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[153], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mcalculate\u001b[49m(\u001b[38;5;241m5\u001b[39m, \u001b[38;5;241m5\u001b[39m)\n", "\u001b[0;31mNameError\u001b[0m: name 'calculate' is not defined" ] } ], "source": [ "calculate(5, 5)" ] }, { "cell_type": "code", "execution_count": 154, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "math domain error", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[154], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mmath\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43msqrt\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m-\u001b[39;49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m)\u001b[49m\n", "\u001b[0;31mValueError\u001b[0m: math domain error" ] } ], "source": [ "math.sqrt(-1)" ] }, { "cell_type": "code", "execution_count": 155, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "module 'math' has no attribute 'my_func'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[155], line 3\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mmath\u001b[39;00m\n\u001b[0;32m----> 3\u001b[0m \u001b[43mmath\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmy_func\u001b[49m(\u001b[38;5;241m2\u001b[39m)\n", "\u001b[0;31mAttributeError\u001b[0m: module 'math' has no attribute 'my_func'" ] } ], "source": [ "import math\n", "\n", "math.my_func(2)" ] }, { "cell_type": "code", "execution_count": 156, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "'str' object has no attribute 'my_func'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[156], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mjason\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmy_func\u001b[49m()\n", "\u001b[0;31mAttributeError\u001b[0m: 'str' object has no attribute 'my_func'" ] } ], "source": [ "\"jason\".my_func()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Classes: Creating Your Own Objects" ] }, { "cell_type": "code", "execution_count": 157, "metadata": {}, "outputs": [], "source": [ "class JasonStrimpel:\n", " pass\n", "\n", "\n", "class ThisIsMyClass:\n", " pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 158, "metadata": {}, "outputs": [], "source": [ "# Define a new class called `Thing` that is derived from the base Python object\n", "class Car(object):\n", " color = \"red\"" ] }, { "cell_type": "code", "execution_count": 159, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "__main__.Car" ] }, "execution_count": 159, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Create \"instances\" of our new classes\n", "a = Car()\n", "b = Car()\n", "c = Car()\n", "\n", "type(c)" ] }, { "cell_type": "code", "execution_count": 160, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'red'" ] }, "execution_count": 160, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c.color" ] }, { "cell_type": "code", "execution_count": 161, "metadata": {}, "outputs": [], "source": [ "# Interact with a DictThing instance just as you would a normal dictionary\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": 162, "metadata": {}, "outputs": [], "source": [ "d = DictThing()" ] }, { "cell_type": "code", "execution_count": 163, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'name': 'Javier',\n", " 'fav_foods': ['chicken', 'veg', 'candy'],\n", " 'rain': True,\n", " 'cars': 'a lot'}" ] }, "execution_count": 163, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict_1" ] }, { "cell_type": "code", "execution_count": 164, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "'dict' object has no attribute 'my_property'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "Cell \u001b[0;32mIn[164], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mdict_1\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mmy_property\u001b[49m\n", "\u001b[0;31mAttributeError\u001b[0m: 'dict' object has no attribute 'my_property'" ] } ], "source": [ "dict_1.my_property" ] }, { "cell_type": "code", "execution_count": 165, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'age': 13, 'fav_foods': ['pizza', 'sushi', 'pad thai', 'waffles'], 'fav_color': 'green'}\n" ] } ], "source": [ "d.update(\n", " {\n", " \"age\": 13,\n", " \"fav_foods\": [\"pizza\", \"sushi\", \"pad thai\", \"waffles\"],\n", " \"fav_color\": \"green\",\n", " }\n", ")\n", "print(d)" ] }, { "cell_type": "code", "execution_count": 166, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I am a \"DictThing\"\n" ] } ], "source": [ "print(d.my_property)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Creating An Initializer Method For Classes" ] }, { "cell_type": "code", "execution_count": 167, "metadata": {}, "outputs": [], "source": [ "class Car:\n", "\n", " color = \"red\"\n", "\n", " def __init__(self):\n", " print(f\"The car is going fast.\")" ] }, { "cell_type": "code", "execution_count": 168, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The car is going fast.\n" ] } ], "source": [ "a = Car()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Defining Attributes & Methods" ] }, { "cell_type": "code", "execution_count": 169, "metadata": {}, "outputs": [], "source": [ "class Car:\n", "\n", " color = \"red\"\n", "\n", " def __init__(self):\n", " print(f\"The car is going fast.\")\n", "\n", " def drive(self, how_fast):\n", " return f\"The {self.color} car drives {how_fast} mph.\"" ] }, { "cell_type": "code", "execution_count": 170, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The car is going fast.\n", "The car is going fast.\n" ] } ], "source": [ "car_a = Car()\n", "car_b = Car()" ] }, { "cell_type": "code", "execution_count": 171, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'red'" ] }, "execution_count": 171, "metadata": {}, "output_type": "execute_result" } ], "source": [ "car_a.color" ] }, { "cell_type": "code", "execution_count": 172, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'red'" ] }, "execution_count": 172, "metadata": {}, "output_type": "execute_result" } ], "source": [ "car_b.color" ] }, { "cell_type": "code", "execution_count": 173, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'The red car drives 55 mph.'" ] }, "execution_count": 173, "metadata": {}, "output_type": "execute_result" } ], "source": [ "car_b.drive(55)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# `self` - Setting Attributes & Methods" ] }, { "cell_type": "code", "execution_count": 174, "metadata": {}, "outputs": [], "source": [ "class Car:\n", "\n", " def __init__(self, color, make):\n", " self.color = color\n", " self.color_cap = color.upper()\n", " self.make = make\n", "\n", " def mph_to_kph(self, mph):\n", " return mph * 1.60934\n", "\n", " def drive(self, how_fast):\n", " return f\"The {self.color} {self.make} drives {how_fast} mph.\"\n", "\n", " def drive_in_kph(self, how_fast):\n", " kph = self.mph_to_kph(how_fast)\n", " return f\"The {self.color} {self.make} drives {kph} kph.\"" ] }, { "cell_type": "code", "execution_count": 175, "metadata": {}, "outputs": [], "source": [ "car_a = Car(\"Black\", \"Tahoe\")" ] }, { "cell_type": "code", "execution_count": 176, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'The Black Tahoe drives 88.5137 kph.'" ] }, "execution_count": 176, "metadata": {}, "output_type": "execute_result" } ], "source": [ "car_a.drive_in_kph(55)" ] }, { "cell_type": "code", "execution_count": 177, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'The Black Audi drives 160.934 kph.'" ] }, "execution_count": 177, "metadata": {}, "output_type": "execute_result" } ], "source": [ "car_b = Car(\"Black\", \"Audi\")\n", "car_b.drive_in_kph(100)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.5" } }, "nbformat": 4, "nbformat_minor": 4 }