{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python tips and tricks\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Assign Multiple Variables on One Line" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5 10\n" ] } ], "source": [ "x, y = 5, 10\n", "print(x, y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Print colored text" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[91mError: This is \u001b[96mcyan. \u001b[92mContinue?\n" ] } ], "source": [ "print(f\"\\033[91mError: This is \\033[96mcyan. \\033[92mContinue?\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How to raise a number to a power" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3125\n" ] } ], "source": [ "x = 5**5\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Banker's Rounding - half towards even" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "12\n" ] } ], "source": [ "print(round(10.5)) #down to 10\n", "print(round(11.5)) #up to 12" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Underscores in numbers" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "999999999\n" ] } ], "source": [ "my_bank_account = 999_999_999\n", "print(my_bank_account)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Open a web browser" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "import webbrowser\n", "\n", "#webbrowser.open('https://www.google.com') #commented out because it's annoying" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Concatenation without +" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello this is a message\n" ] } ], "source": [ "message = \"Hello this \" \"is a message\"\n", "print(message)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Split string on multiple lines" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is a really long message that I split up over multiple lines for convenience sake. The actual output is the same\n" ] } ], "source": [ "print(\"This is a really long message that I split up over \"\n", "\"multiple lines for convenience sake. \"\n", "\"The actual output is the same\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multiline string" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is a really long message that I split up over multiple lines for convenience sake.\n", "The output is affected.\n" ] } ], "source": [ "# \\ to ignore newline. No spaces after!\n", "print('''This is a really long message that I split up over \\\n", "multiple lines for convenience sake.\n", "The output is affected.''')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Multiline comment" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "10\n" ] } ], "source": [ "print(5)\n", "\"\"\"\n", "print('ignored!')\n", "print('pretty cool huh')\n", "\"\"\"\n", "print(10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Get last element of list" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "data = [1, 2, 3]\n", "print(data[-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reverse a list with slicing" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, 2, 1]\n" ] } ], "source": [ "data = [1, 2, 3]\n", "print(data[::-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Reverse with method" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, 2, 1]\n" ] } ], "source": [ "data = [1, 2, 3]\n", "data.reverse()\n", "print(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Substring with in" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n" ] } ], "source": [ "if 'You' in 'YouTube':\n", " print('YouTube'.index('You')) #can throw error" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Single line if" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n" ] } ], "source": [ "if 'You' in 'YouTube': print('YouTube'.index('You')) #can throw error" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Get index with find" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'YouTube'.find('flowers')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using id to get identity -- guarenteed to be unique for each object" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "140479393791744\n" ] } ], "source": [ "data = {\"Caleb\": 5}\n", "print(id(data))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Aliases" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An alias is another name for something\n", "We use an alias if we want two variables pointing to the same data\n", "or if we want functions to be able to modify arguments passed it" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "140479393791904\n", "140479393791904\n", "{'Caleb': 5, 'Erin': 13}\n" ] } ], "source": [ "data1 = {\"Caleb\": 5}\n", "data2 = data1\n", "data2['Erin'] = 13\n", "\n", "print(id(data1))\n", "print(id(data2))\n", "print(data1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Primitive types are immutable" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4311143040\n", "4311142752\n", "1\n" ] } ], "source": [ "data1 = 10\n", "data2 = data1\n", "data2 = 1 #replaced data2\n", "\n", "print(id(data1))\n", "print(id(data2))\n", "print(data2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## in-place methods" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3]\n" ] } ], "source": [ "data = [3, 2, 1]\n", "data.sort()\n", "print(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## replace list vs replace list content" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['C++', 'Go', 'Python']\n", "['C++', 'Go', 'Python']\n", "['new']\n" ] } ], "source": [ "def replace_list(data):\n", " data = ['new']\n", " \n", "def replace_list_content(data):\n", " data[:] = ['new']\n", " \n", "languages = ['C++', 'Go', 'Python']\n", "\n", "print(languages)\n", "replace_list(languages)\n", "print(languages)\n", "replace_list_content(languages)\n", "print(languages)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Copy a list with slicing" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "140479393918480 140479393910944\n" ] } ], "source": [ "languages = ['C++', 'Go', 'Python']\n", "learning = languages[:]\n", "\n", "print(id(languages), id(learning))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Copy a list with method" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "140479393912224 140479393916880\n" ] } ], "source": [ "languages = ['C++', 'Go', 'Python']\n", "learning = languages.copy()\n", "\n", "print(id(languages), id(learning))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using deepcopy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "shallow copy copies each element's address to the new location\n", "This means that if one of the elements is an object itself, the address it points to copied.\n", "Now we have two different lists that point to the same object \n", "Deepcopy goes further by copying any of the objects as well, not just the pointer to them. " ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n", "False\n", "False\n" ] } ], "source": [ "from copy import deepcopy\n", "\n", "tech = ['C++', 'Go', 'Python', ['html', 'css', 'pics']]\n", "learning = tech.copy()\n", "print(id(tech) == id(learning))\n", "print(id(tech[-1]) == id(learning[-1])) #true with shallow copy\n", "\n", "learning = deepcopy(tech)\n", "print(id(tech) == id(learning))\n", "print(id(tech[-1]) == id(learning[-1]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Concatenate lists" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4, 5, 6]\n" ] } ], "source": [ "beginning = [1, 2, 3]\n", "end = [4, 5, 6]\n", "print(beginning + end)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Comparing not vs is None" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "not will check for implicit false values\n", "which includes empty lists, zero, and False" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "True\n", "True\n" ] } ], "source": [ "data1 = []\n", "data2 = None\n", "print(not data1)\n", "print(data1 is None)\n", "\n", "print(not data2) # None evaluates to false\n", "print(data2 is None)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check empty list" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "False\n" ] } ], "source": [ "data = []\n", "\n", "#often seen:\n", "#print(len(data) == 0): #not the Python way. Throws if None\n", "\n", "print(not data) #empty, None, or zero \n", "\n", "#You can also check these things:\n", "print(data is not None) #anything but None\n", "print(data is None) #None only\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Check if exists" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True True\n", "False False\n", "True True\n" ] } ], "source": [ "age = 16\n", "\n", "print('age' in locals(), 'age' in globals())\n", "del age\n", "print('age' in locals(), 'age' in globals())\n", "\n", "age = None\n", "print('age' in locals(), 'age' in globals())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Print end =\" \" to change ending" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C C++ Java C# Python Go Rust \n" ] } ], "source": [ "for language in ['C', 'C++', 'Java', 'C#', 'Python', 'Go', 'Rust']:\n", " print(language, end=\" \")\n", "print(\"\") #to go to next line for the next output" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Print multiple elements with commas " ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Caleb 25 ['English', 'C++', 'Python']\n" ] } ], "source": [ "name = \"Caleb\"\n", "age = 25\n", "favorite_languages = [\"English\", \"C++\", \"Python\"]\n", "\n", "print(name, age, favorite_languages)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## String formatting for easy string making" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using commas to separate variables within print is nice and convenient, but what if you want a string variable?\n", "Using commas actually creates a tuple (not what we want).\n", "The common solution of using string concatentation is ugly. \n", "Instead, use f strings!" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "('Caleb', 25)\n", "My name is Caleb. I am 25 years old.\n", "My name is Caleb. I am 25 years old.\n" ] } ], "source": [ "message = name, age\n", "print(message) #makes a tuple\n", "\n", "print(\"My name is \" + str(name) + \". I am \" + str(age) + \" years old.\")\n", "\n", "print(f\"My name is {name}. I am {age} years old.\") #implict string conversion" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Return multiple values and assign to multiple variables" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(5, 10, 15, 20)\n", "5 10 15 20\n" ] } ], "source": [ "def get_position():\n", " #get from user or something\n", " return 5, 10, 15, 20\n", "\n", "print(get_position()) \n", "x, y, z, a = get_position()\n", "print(x, y, z, a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Ternary conditional operator" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "admin\n", "visitor\n" ] } ], "source": [ "#You'll typically see:\n", "reputation = 30\n", "if reputation > 25:\n", " name = \"admin\"\n", "else:\n", " name = \"visitor\"\n", "print(name)\n", "\n", "reputation = 20\n", "name = \"admin\" if reputation > 25 else \"visitor\"\n", "print(name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Else can be used with loop" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Option 1 is yes or no\n", "option 2 uses a flag variable. can also remove break and continue iteration\n", "option 3 else will execute if no break is found (in other words--No cats)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "eww a cat\n", "dog dog cat eww a cat\n", "dog dog bird chicken dog No cat found\n" ] } ], "source": [ "pets = ['dog', 'dog', 'cat', 'bird', 'chicken', 'dog']\n", "\n", "if 'cat' in pets: print(\"eww a cat\") #option 1\n", " \n", "cat_found = False \n", "for pet in pets:\n", " print(pet, end=\" \") #do something with each element if needed\n", " if pet == 'cat':\n", " cat_found = True #could count elements\n", " break \n", "\n", "if cat_found: print(\"eww a cat\") #option 2\n", " \n", "\n", "pets.remove('cat')\n", "for pet in pets:\n", " print(pet, end=\" \")\n", " if pet == 'cat':\n", " break\n", " \n", "else: #no break -- option 3\n", " print(\"No cat found\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Use range to generate lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "type of range is list in python 2. Make sure you're running with Python 3. \n", "For me, the python command defaults to Python2 so I use the python3 command" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1 2 3 4 5 6 7 8 9 \n", "[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]\n" ] } ], "source": [ "for i in range(10):\n", " print(i, end=\" \")\n", "print(type(range(10)))\n", "\n", "print(list(range(0, 100, 3)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Unpack operator" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Given a list you can split it into individual values" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "moving character to 5 10 15\n" ] } ], "source": [ "def move_position(x, y, z):\n", " print(f'moving character to {x} {y} {z}')\n", " \n", "pos = [5, 10, 15]\n", "move_position(*pos) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How to do nothing in Python with pass\n", "Python doesn't have { }, so this is how we do the equiv in Python" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [], "source": [ "def move_position(x, y, z):\n", " pass" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Remove list duplicates" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['chicken', 'bird', 'dog', 'cat']\n" ] } ], "source": [ "pets = ['dog', 'dog', 'cat', 'bird', 'chicken', 'dog']\n", "pet_types = list(set(pets))\n", "print(pet_types)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using in instead of complex conditional - Check against list of values" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "cancelled\n" ] } ], "source": [ "weather = \"rainy\"\n", "\n", "if weather in ['rainy', 'cold', 'snowy']:\n", " print(\"cancelled\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## complex conditional - Evaluate against any conditon" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "You're an admin\n" ] } ], "source": [ "age = 21\n", "reputation = 20\n", "\n", "conditions = [ \n", " age >= 21,\n", " reputation > 25\n", "]\n", " \n", "if any(conditions):\n", " print(\"You're an admin\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## complex conditional - Evaluate against all conditions" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "You're a standard user\n" ] } ], "source": [ "age = 21\n", "reputation = 20\n", "\n", "conditions = [ \n", " age >= 21,\n", " reputation > 25\n", "]\n", " \n", "if all(conditions):\n", " print(\"You're an admin\")\n", "else:\n", " print(\"You're a standard user\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Split from string to multiple variables" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Caleb Curry\n", "[1, 2, 3]\n" ] } ], "source": [ "full_name = \"Caleb Curry\"\n", "first, last = full_name.split() #returns list but can assign to individual variables\n", "print(first, last)\n", "\n", "data = \"1 2 3\"\n", "data = [int(d) for d in data.split()]\n", "print(data)\n", "\n", "#This is most useful to get multiple inputs separated by spaces:\n", "#first, last = input().split()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Join data " ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Caleb Curry\n" ] } ], "source": [ "names = [\"Caleb\", \"Curry\"]\n", "full_name = \" \".join(names)\n", "print(full_name)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Removing certain elements from a list" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['dog', 'dog', 'bird', 'dog']\n" ] } ], "source": [ "pets = ['dog', 'dog', 'cat', 'bird', 'cat','chicken', 'cat', 'dog']\n", "\n", "clean_pets = [pet for pet in pets if pet not in['cat','chicken']]\n", "print(clean_pets)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Iterate backwards with reversed" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dog cat chicken cat bird cat dog dog " ] } ], "source": [ "pets = ['dog', 'dog', 'cat', 'bird', 'cat','chicken', 'cat', 'dog']\n", "for pet in reversed(pets):\n", " print(pet, end=\" \")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## No do-while loop in python" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Choose an option:\n", "1. play game\n", "2. load game\n", "3. high scores\n", "4. quit\n" ] } ], "source": [ "while True:\n", " print(\"\"\"Choose an option:\n", "1. play game\n", "2. load game\n", "3. high scores\n", "4. quit\"\"\")\n", " #if input() == \"4\":\n", " if True: \n", " break\n", " \n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Assigning a function to a variable - just don’t use ()" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Doing things....\n" ] } ], "source": [ "def done():\n", " print(\"done\")\n", " \n", "def do_something(callback):\n", " print(\"Doing things....\")\n", " \n", "do_something(done)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Wait with time.sleep" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Doing things....\n" ] } ], "source": [ "import time\n", "def done():\n", " print(\"done\")\n", " \n", "def do_something(callback):\n", " time.sleep(1)\n", " print(\"Doing things....\")\n", " \n", "do_something(done)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Get index with for loop" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 dog dog\n", "1 dog dog\n", "2 cat dog\n", "3 bird cat\n", "4 cat bird\n", "5 chicken cat\n", "6 cat chicken\n", "7 dog cat\n" ] } ], "source": [ "pets = ['dog', 'dog', 'cat', 'bird', 'cat','chicken', 'cat', 'dog']\n", "\n", "for i, pet in enumerate(pets):\n", " print(i, pet, pets[i-1]) #can use index in statements now" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Flatten a list with nested list comprehension" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[5, 10, 15, 20, 25, 30, 35, 40]\n" ] } ], "source": [ "pairs = [[5, 10],[15, 20],[25, 30, 35, 40]]\n", "\n", "flat = []\n", "for pair in pairs:\n", " for item in pair:\n", " flat.append(item)\n", "\n", "print(flat)\n", "\n", "flat_list = [item for pair in pairs for item in pair]\n", "#notice important sections: \n", "#for pair in pairs\n", "#for item in pair" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Wrapping a Primitive to change within function\n", "You can also use a list for simplicity" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3125\n" ] } ], "source": [ "class Container:\n", " def __init__(self, data):\n", " self.data = data\n", " \n", "def calculate(input):\n", " input.data **= 5\n", " \n", "container = Container(5)\n", "calculate(container)\n", "print(container.data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Compare identity with is" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "140479253959632 140479253959504\n", "False\n", "False\n" ] } ], "source": [ "c1 = Container(5)\n", "c2 = Container(5)\n", "print(id(c1), id(c2))\n", "print(id(c1) == id(c2)) \n", "\n", "print(c1 is c2) #better code" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Add a method dynamically" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "def __eq__(self, other):\n", " return self.data == other.data\n", "\n", "Container.__eq__ = __eq__\n", "\n", "print(Container.__eq__)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Compare by Value" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n" ] } ], "source": [ "c1 = Container(5)\n", "c2 = Container(5)\n", "\n", "print(c1 == c2) #same values\n", "print(c1 is c2) #different objects" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Class parenthesis optional but not function parenthesis\n", "The () are optional for classes. Only needed if you're inheriting. However, function () are always required when defining." ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [], "source": [ "class Container():\n", " def __init__(self, data):\n", " self.data = data\n", "\n", "class Container: \n", " def __init__(self, data):\n", " self.data = data\n", "\n", "#def function:\n", "# print(\"oopsies\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Get current date and time" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2020-12-03 14:08:16.251001\n", "3 12 2020 14 8 16\n" ] } ], "source": [ "from datetime import datetime\n", "now = datetime.now()\n", "print(now)\n", "print(now.day, now.month, now.year, now.hour, now.minute, now.second)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Countdown\n", "You can do this in a loop if you need." ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-3 days, 9:51:43.745464\n" ] } ], "source": [ "from datetime import datetime\n", "now = datetime.now()\n", "end = datetime(2020, 12, 1)\n", "print(end-now) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Elapsed time" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "0:00:02.298135\n", "2 298135\n" ] } ], "source": [ "from datetime import datetime\n", "start = datetime.now()\n", "\n", "for i in range(100_000_000): #to pass time\n", " pass\n", "\n", "end = datetime.now()\n", "\n", "print(type(end-start))\n", "elapsed = end-start\n", "print(elapsed)\n", "print(elapsed.seconds, elapsed.microseconds)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Parentheses for operations with object members\n", "operator precedence - dot operator comes ahead of +/- operator." ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "16\n", "Wrong\n" ] } ], "source": [ "now = datetime.now()\n", "then = datetime.now()\n", "\n", "elapsed = (then-now).microseconds\n", "print(elapsed)\n", "\n", "try:\n", " print(then-now.microseconds)\n", "except:\n", " print(\"Wrong\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Runtime error vs syntax error\n", "Syntax errors are impossible to be correct and will prevent execution \n", "Runtime errors deal with incorrect data found during runtime" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Wrong\n" ] } ], "source": [ "#def function:\n", "# print('wrong syntax')\n", " \n", "try:\n", " print(then-now.microseconds)\n", "except:\n", " print(\"Wrong\") \n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Get a random number" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n" ] } ], "source": [ "from random import randint\n", "print(randint(0, 12)) #inclusive #inclusive" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Import with Alias\n", "This capability came in handy for me when I needed a module \n", "to be a specific name for my code to work" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "52 1\n" ] } ], "source": [ "def randint():\n", " return 52\n", " \n", "from random import randint as r\n", " \n", "print(randint(), r(0, 100))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Generators and Yield" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1 1 2 3\n", "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 " ] } ], "source": [ "def fib(count):\n", " a, b = 0, 1\n", " while count:\n", " yield a\n", " a, b, = b, b + a\n", " count -= 1\n", "\n", "\n", "gen = fib(100)\n", "print(next(gen), next(gen), next(gen), next(gen), next(gen))\n", "\n", "for i in fib(20):\n", " print(i, end=\" \")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## infinite number" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "inf\n", "inf inf\n" ] } ], "source": [ "import math\n", "#inf = (float('inf')) #other way without math.\n", "print(math.inf)\n", "\n", "inf = math.inf\n", "print(inf, inf-1) #always infinity" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Infinite generator\n", "You could make an infinite loop with a yield or use float('inf')) as the counter for more versatility \n", "(You can use a smaller number if you desire a certain number of elements) \n", "Bounded generator was used in documentation - https://wiki.python.org/moin/Generators \n", "This stopping point allows you to do things like get the sum." ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1 1 2 3 5 8 13 21 34 55 89 144 " ] } ], "source": [ "import math\n", "\n", "def fib(count):\n", " a, b = 0, 1\n", " while count:\n", " yield a\n", " a, b, = b, b + a\n", " count -= 1\n", "\n", "f = fib(math.inf)\n", "for i in f:\n", " if i >= 200: break\n", " print(i, end=\" \")\n", " i += 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## list from generator" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0.0, 1.0, 1.0, 1.414, 1.732, 2.236, 2.828, 3.606, 4.583, 5.831]\n" ] } ], "source": [ "import math\n", "\n", "def fib(count):\n", " a, b = 0, 1\n", " while count:\n", " yield a\n", " a, b, = b, b + a\n", " count -= 1\n", " \n", "f = fib(10)\n", "data = [round(math.sqrt(i), 3) for i in f]\n", "print(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## itertools for simple infinite generator\n", "The generator function could be simpler without having to take a max count property \n", "This can be done easily with itertools. " ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]\n" ] } ], "source": [ "import itertools\n", "\n", "def fib():\n", " a, b = 0, 1\n", " while True:\n", " yield a\n", " a, b, = b, b + a\n", " \n", "print(list(itertools.islice(fib(), 20)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Iterate through custom type with __iter__" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "10\n", "15\n", "20\n" ] } ], "source": [ "class Node:\n", " def __init__(self, data, next_node=None):\n", " self.data = data\n", " self.next = next_node\n", "\n", "class LinkedList:\n", "\n", " def __init__(self, start):\n", " self.start = start\n", " \n", " def __iter__(self):\n", " node = self.start\n", " while node:\n", " yield node\n", " node = node.next\n", " \n", "ll = LinkedList(Node(5, Node(10, Node(15, Node(20)))))\n", "for node in ll:\n", " print(node.data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Falsey for custom types (not)" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "4\n", "True\n" ] } ], "source": [ "print(not []) #true because it's empty\n", "print(len([]) == 0) #This is how not is evaluated\n", "\n", "def __len__(self):\n", " count = 0\n", " for i in self:\n", " count += 1\n", " return count\n", " \n", "\n", "LinkedList.__len__ = __len__\n", " \n", " \n", "ll = LinkedList(Node(5, Node(10, Node(15, Node(20)))))\n", "print(len(ll))\n", "ll = LinkedList(None)\n", "print(not ll)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Combine two lists as a list of lists. " ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('Caleb', 100), ('Corey', 250), ('Chris', 30), ('Samantha', 600)]\n" ] } ], "source": [ "names = ['Caleb', 'Corey', 'Chris', 'Samantha']\n", "points = [100, 250, 30, 600]\n", "\n", "zipped = list(zip(names, points))\n", "\n", "print(zipped)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Convert list of tuples to list of lists" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[['Caleb', 100], ['Corey', 250], ['Chris', 30], ['Samantha', 600]]\n" ] } ], "source": [ "names = ['Caleb', 'Corey', 'Chris', 'Samantha']\n", "points = [100, 250, 30, 600]\n", "\n", "zipped = list(zip(names, points))\n", "\n", "data = [list(item) for item in zipped]\n", "print(data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Preserving all data when zipping with zip_longest" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[('Caleb', 100), ('Corey', 250), ('Chris', 30), ('Samantha', 600)]\n", "[('Caleb', 100), ('Corey', 250), ('Chris', 30), ('Samantha', 600), ('Hannah', None), ('Kelly', None)]\n" ] } ], "source": [ "names = ['Caleb', 'Corey', 'Chris', 'Samantha', \"Hannah\", \"Kelly\"]\n", "points = [100, 250, 30, 600]\n", "zipped = list(zip(names, points))\n", "print(zipped)\n", "\n", "from itertools import zip_longest\n", "names = ['Caleb', 'Corey', 'Chris', 'Samantha', \"Hannah\", \"Kelly\"]\n", "points = [100, 250, 30, 600]\n", "\n", "zipped = list(zip_longest(names, points))\n", "\n", "print(zipped)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Default Arguments" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[['Caleb', 100], ['Corey', 250], ['Chris', 30], ['Samantha', 600], ['Hannah', None], ['Kelly', None]]\n" ] } ], "source": [ "from itertools import zip_longest\n", "\n", "\n", "def zip_lists(list1=[], list2=[], longest=True):\n", " if longest:\n", " return [list(item) for item in zip_longest(list1, list2)]\n", " else:\n", " return [list(item) for item in zip(list1, list2)]\n", " \n", "names = ['Caleb', 'Corey', 'Chris', 'Samantha', \"Hannah\", \"Kelly\"]\n", "points = [100, 250, 30, 600]\n", "\n", "print(zip_lists(names, points))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Keyword Arguments\n", "\n", "When you have default values, you can pass arugments by name\n", "positional arguments must remain on the left\n", "You can pass named arguments in any order and can skip them even." ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[None, 'Caleb']]\n" ] } ], "source": [ "from itertools import zip_longest\n", "\n", "\n", "def zip_lists(list1=[], list2=[], longest=True):\n", " if longest:\n", " return [list(item) for item in zip_longest(list1, list2)]\n", " else:\n", " return [list(item) for item in zip(list1, list2)]\n", "\n", "\n", "print(zip_lists(longest=True, list2=['Caleb']))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Get the Python version" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.7.8\n" ] } ], "source": [ "from platform import python_version\n", "\n", "print(python_version())" ] } ], "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.7.8" } }, "nbformat": 4, "nbformat_minor": 4 }