├── .gitignore ├── README.ipynb ├── README.md ├── cheatsheet.01.basics.ipynb ├── cheatsheet.02.Built-in.Functions.ipynb ├── cheatsheet.03.Control.Flow.ipynb ├── cheatsheet.04.Functions.ipynb ├── cheatsheet.05.Lists.and.Tuples.ipynb ├── cheatsheet.06.Dictionaries.ipynb ├── cheatsheet.07.Sets.ipynb ├── cheatsheet.08.Comprehensions.ipynb ├── cheatsheet.09.Manipulating.Strings.ipynb ├── cheatsheet.10.String.Formatting.ipynb ├── cheatsheet.11.Regular.Expressions.ipynb ├── cheatsheet.12.File.and.Directory.Paths.ipynb ├── cheatsheet.13.Reading.and.Writing.Files.ipynb ├── cheatsheet.14.JSON.and.YAML.ipynb ├── cheatsheet.15.Exception.Handling.ipynb ├── cheatsheet.16.Debugging.ipynb ├── cheatsheet.17.Args.and.Kwargs.ipynb ├── cheatsheet.18.Context.Manager.ipynb ├── cheatsheet.19.OOP.Basics.ipynb ├── cheatsheet.20.Dataclasses.ipynb ├── cheatsheet.21.setup.ipynb ├── cheatsheet.22.Main.top-level.script.ipynb ├── cheatsheet.23.Virtual.Environment.ipynb ├── standard.library.01.Copy.ipynb ├── standard.library.02.Datetime.ipynb ├── standard.library.03.Itertools.ipynb ├── standard.library.04.Json.ipynb ├── standard.library.05.Os.ipynb ├── standard.library.06.Pathlib.ipynb ├── standard.library.07.Random.ipynb ├── standard.library.08.Shelve.ipynb └── standard.library.09.Zipfile.ipynb /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints 2 | .jupyter 3 | .DS_Store -------------------------------------------------------------------------------- /README.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "6be3b8de-de49-414c-a248-7d02e4d2a265", 6 | "metadata": {}, 7 | "source": [ 8 | "# README\n", 9 | "\n", 10 | "Most of the content in this \"tutorial\" was adapted from wilfredinni's python-cheatsheet ([GitHub repo](https://github.com/wilfredinni/python-cheatsheet)), which has been transformed from `.html` format into an interactive `.ipynb` format for seamless execution in [Jupyter Notebook](https://jupyter.org/) or [JupyterLab Desktop](https://github.com/jupyterlab/jupyterlab-desktop).\n", 11 | "\n", 12 | "## Table of Content\n", 13 | "\n", 14 | "* [README.ipynb](README.ipynb)\n", 15 | "* [cheatsheet.01.basics.ipynb](cheatsheet.01.basics.ipynb)\n", 16 | "* [cheatsheet.02.Built-in.Functions.ipynb](cheatsheet.02.Built-in.Functions.ipynb)\n", 17 | "* [cheatsheet.03.Control.Flow.ipynb](cheatsheet.03.Control.Flow.ipynb)\n", 18 | "* [cheatsheet.04.Functions.ipynb](cheatsheet.04.Functions.ipynb)\n", 19 | "* [cheatsheet.05.Lists.and.Tuples.ipynb](cheatsheet.05.Lists.and.Tuples.ipynb)\n", 20 | "* [cheatsheet.06.Dictionaries.ipynb](cheatsheet.06.Dictionaries.ipynb)\n", 21 | "* [cheatsheet.07.Sets.ipynb](cheatsheet.07.Sets.ipynb)\n", 22 | "* [cheatsheet.08.Comprehensions.ipynb](cheatsheet.08.Comprehensions.ipynb)\n", 23 | "* [cheatsheet.09.Manipulating.Strings.ipynb](cheatsheet.09.Manipulating.Strings.ipynb)\n", 24 | "* [cheatsheet.10.String.Formatting.ipynb](cheatsheet.10.String.Formatting.ipynb)\n", 25 | "* [cheatsheet.11.Regular.Expressions.ipynb](cheatsheet.11.Regular.Expressions.ipynb)\n", 26 | "* [cheatsheet.12.File.and.Directory.Paths.ipynb](cheatsheet.12.File.and.Directory.Paths.ipynb)\n", 27 | "* [cheatsheet.13.Reading.and.Writing.Files.ipynb](cheatsheet.13.Reading.and.Writing.Files.ipynb)\n", 28 | "* [cheatsheet.14.JSON.and.YAML.ipynb](cheatsheet.14.JSON.and.YAML.ipynb)\n", 29 | "* [cheatsheet.15.Exception.Handling.ipynb](cheatsheet.15.Exception.Handling.ipynb)\n", 30 | "* [cheatsheet.16.Debugging.ipynb](cheatsheet.16.Debugging.ipynb)\n", 31 | "* [cheatsheet.17.Args.and.Kwargs.ipynb](cheatsheet.17.Args.and.Kwargs.ipynb)\n", 32 | "* [cheatsheet.18.Context.Manager.ipynb](cheatsheet.18.Context.Manager.ipynb)\n", 33 | "* [cheatsheet.19.OOP.Basics.ipynb](cheatsheet.19.OOP.Basics.ipynb)\n", 34 | "* [cheatsheet.20.Dataclasses.ipynb](cheatsheet.20.Dataclasses.ipynb)\n", 35 | "* [cheatsheet.21.setup.ipynb](cheatsheet.21.setup.ipynb)\n", 36 | "* [cheatsheet.22.Main.top-level.script.ipynb](cheatsheet.22.Main.top-level.script.ipynb)\n", 37 | "* [cheatsheet.23.Virtual.Environment.ipynb](cheatsheet.23.Virtual.Environment.ipynb)\n", 38 | "* [standard.library.01.Copy.ipynb](standard.library.01.Copy.ipynb)\n", 39 | "* [standard.library.02.Datetime.ipynb](standard.library.02.Datetime.ipynb)\n", 40 | "* [standard.library.03.Itertools.ipynb](standard.library.03.Itertools.ipynb)\n", 41 | "* [standard.library.04.Json.ipynb](standard.library.04.Json.ipynb)\n", 42 | "* [standard.library.05.Os.ipynb](standard.library.05.Os.ipynb)\n", 43 | "* [standard.library.06.Pathlib.ipynb](standard.library.06.Pathlib.ipynb)\n", 44 | "* [standard.library.07.Random.ipynb](standard.library.07.Random.ipynb)\n", 45 | "* [standard.library.08.Shelve.ipynb](standard.library.08.Shelve.ipynb)\n", 46 | "* [standard.library.09.Zipfile.ipynb](standard.library.09.Zipfile.ipynb)\n" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "id": "7c5672aa-d68f-4abf-9664-71618ea4ac4a", 52 | "metadata": {}, 53 | "source": [ 54 | "## What is programming?\n", 55 | "\n", 56 | "At its core, programming is all about handling data. Think of programmers as data wranglers, using coding languages to shape and channel data, which are just representations of real-world things and concepts.\n", 57 | "\n", 58 | "To make life easier, every programming language comes with several basic data types, such as numbers, strings, or binary values. Building on these, you've got more complex types like lists (or arrays), dictionaries, maps, and objects.\n", 59 | "\n", 60 | "Imagine data stored in variables as labeled boxes. These labels help programmers keep track of what type of data is inside. As a program runs, it’s essentially moving and transforming these boxes of data through various statements and functions.\n", 61 | "\n", 62 | "Data wrangling requires a structured approach, and that's where \"flow control\" comes into play. It's the programming equivalent of a traffic signal, directing how tasks flow in the code. Sometimes actions run one after another (that's sequence), sometimes they repeat (loops), and sometimes they only happen under certain conditions (conditionals).\n", 63 | "\n", 64 | "In any programming language, a statement is just an instruction to do something with data. And when tasks get complex, they can be bundled into \"functions\" for efficiency and reuse throughout the code.\n", 65 | "\n", 66 | "As a beginner, grasp these concepts, and you're off to a solid start. And yes, being able to explain your code in plain English is a superpower in its own right!" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "id": "78efccf9-a8be-48c8-88c9-9ba4f227bdc4", 72 | "metadata": {}, 73 | "source": [ 74 | "## What is Python?\n", 75 | "\n", 76 | "Python is a programming language that is known for its simplicity, ease of use, and beginner-friendly nature. It is also widely popular in the field of artificial intelligence (AI)." 77 | ] 78 | }, 79 | { 80 | "cell_type": "markdown", 81 | "id": "d72a5017-ee85-4a7b-b828-e814d3ef9838", 82 | "metadata": {}, 83 | "source": [ 84 | "## Setting up the Development Environment\n", 85 | "\n", 86 | "To set up a development environment on your computer, you can follow these steps:\n", 87 | "\n", 88 | "1. Install Homebrew by running the following command in your terminal:\n", 89 | "\n", 90 | "```bash\n", 91 | "/bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"\n", 92 | "```\n", 93 | "\n", 94 | "2. Install JupyterLab Desktop using Homebrew by running the following command in your terminal:\n", 95 | "\n", 96 | "```bash\n", 97 | "brew install --cask jupyterlab\n", 98 | "```\n", 99 | "\n", 100 | "3. Manually set up the JupyterLab command-line interface (CLI) by running the following commands in your terminal:\n", 101 | "\n", 102 | "```bash\n", 103 | "sudo chmod 755 /Applications/JupyterLab.app/Contents/Resources/app/jlab\n", 104 | "sudo ln -s /Applications/JupyterLab.app/Contents/Resources/app/jlab /usr/local/bin/jlab\n", 105 | "```\n", 106 | "\n", 107 | "Once you have completed these steps, you can launch JupyterLab Desktop either by typing \"Jupyter\" in Spotlight and clicking on the JupyterLab Desktop icon, or by using the CLI command \"jlab\" in the terminal.\n", 108 | "\n", 109 | "Now you are ready to start using JupyterLab for your Python development." 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "id": "9341e4cd-9a3a-4445-b6b4-11b036015eeb", 115 | "metadata": {}, 116 | "source": [ 117 | "## Get this tutorial to local\n", 118 | "\n", 119 | "1. Install `git` by running the following command in your terminal:\n", 120 | "\n", 121 | "```bash\n", 122 | "brew install git\n", 123 | "```\n", 124 | "\n", 125 | "2. Clone this repo:\n", 126 | "\n", 127 | "``` bash\n", 128 | "mkdir ~/github\n", 129 | "cd ~/github\n", 130 | "git clone ....\n", 131 | "```\n", 132 | "\n", 133 | "3. Launch JupyterLab-Desktop to view notebooks:\n", 134 | "\n", 135 | "```bash\n", 136 | "cd ~/github/...\n", 137 | "jlab .\n", 138 | "```" 139 | ] 140 | } 141 | ], 142 | "metadata": { 143 | "kernelspec": { 144 | "display_name": "Python 3 (ipykernel)", 145 | "language": "python", 146 | "name": "python3" 147 | }, 148 | "language_info": { 149 | "codemirror_mode": { 150 | "name": "ipython", 151 | "version": 3 152 | }, 153 | "file_extension": ".py", 154 | "mimetype": "text/x-python", 155 | "name": "python", 156 | "nbconvert_exporter": "python", 157 | "pygments_lexer": "ipython3", 158 | "version": "3.12.0" 159 | } 160 | }, 161 | "nbformat": 4, 162 | "nbformat_minor": 5 163 | } 164 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # README 2 | 3 | Most of the content in this "tutorial" was adapted from wilfredinni's python-cheatsheet ([GitHub repo](https://github.com/wilfredinni/python-cheatsheet)), which has been transformed from `.html` format into an interactive `.ipynb` format for seamless execution in [Jupyter Notebook](https://jupyter.org/) or [JupyterLab Desktop](https://github.com/jupyterlab/jupyterlab-desktop). 4 | 5 | ## Table of Content 6 | 7 | * [README.ipynb](README.ipynb) 8 | * [cheatsheet.01.basics.ipynb](cheatsheet.01.basics.ipynb) 9 | * [cheatsheet.02.Built-in.Functions.ipynb](cheatsheet.02.Built-in.Functions.ipynb) 10 | * [cheatsheet.03.Control.Flow.ipynb](cheatsheet.03.Control.Flow.ipynb) 11 | * [cheatsheet.04.Functions.ipynb](cheatsheet.04.Functions.ipynb) 12 | * [cheatsheet.05.Lists.and.Tuples.ipynb](cheatsheet.05.Lists.and.Tuples.ipynb) 13 | * [cheatsheet.06.Dictionaries.ipynb](cheatsheet.06.Dictionaries.ipynb) 14 | * [cheatsheet.07.Sets.ipynb](cheatsheet.07.Sets.ipynb) 15 | * [cheatsheet.08.Comprehensions.ipynb](cheatsheet.08.Comprehensions.ipynb) 16 | * [cheatsheet.09.Manipulating.Strings.ipynb](cheatsheet.09.Manipulating.Strings.ipynb) 17 | * [cheatsheet.10.String.Formatting.ipynb](cheatsheet.10.String.Formatting.ipynb) 18 | * [cheatsheet.11.Regular.Expressions.ipynb](cheatsheet.11.Regular.Expressions.ipynb) 19 | * [cheatsheet.12.File.and.Directory.Paths.ipynb](cheatsheet.12.File.and.Directory.Paths.ipynb) 20 | * [cheatsheet.13.Reading.and.Writing.Files.ipynb](cheatsheet.13.Reading.and.Writing.Files.ipynb) 21 | * [cheatsheet.14.JSON.and.YAML.ipynb](cheatsheet.14.JSON.and.YAML.ipynb) 22 | * [cheatsheet.15.Exception.Handling.ipynb](cheatsheet.15.Exception.Handling.ipynb) 23 | * [cheatsheet.16.Debugging.ipynb](cheatsheet.16.Debugging.ipynb) 24 | * [cheatsheet.17.Args.and.Kwargs.ipynb](cheatsheet.17.Args.and.Kwargs.ipynb) 25 | * [cheatsheet.18.Context.Manager.ipynb](cheatsheet.18.Context.Manager.ipynb) 26 | * [cheatsheet.19.OOP.Basics.ipynb](cheatsheet.19.OOP.Basics.ipynb) 27 | * [cheatsheet.20.Dataclasses.ipynb](cheatsheet.20.Dataclasses.ipynb) 28 | * [cheatsheet.21.setup.ipynb](cheatsheet.21.setup.ipynb) 29 | * [cheatsheet.22.Main.top-level.script.ipynb](cheatsheet.22.Main.top-level.script.ipynb) 30 | * [cheatsheet.23.Virtual.Environment.ipynb](cheatsheet.23.Virtual.Environment.ipynb) 31 | * [standard.library.01.Copy.ipynb](standard.library.01.Copy.ipynb) 32 | * [standard.library.02.Datetime.ipynb](standard.library.02.Datetime.ipynb) 33 | * [standard.library.03.Itertools.ipynb](standard.library.03.Itertools.ipynb) 34 | * [standard.library.04.Json.ipynb](standard.library.04.Json.ipynb) 35 | * [standard.library.05.Os.ipynb](standard.library.05.Os.ipynb) 36 | * [standard.library.06.Pathlib.ipynb](standard.library.06.Pathlib.ipynb) 37 | * [standard.library.07.Random.ipynb](standard.library.07.Random.ipynb) 38 | * [standard.library.08.Shelve.ipynb](standard.library.08.Shelve.ipynb) 39 | * [standard.library.09.Zipfile.ipynb](standard.library.09.Zipfile.ipynb) 40 | 41 | 42 | ## What is programming? 43 | 44 | At its core, programming is all about handling data. Think of programmers as data wranglers, using coding languages to shape and channel data, which are just representations of real-world things and concepts. 45 | 46 | To make life easier, every programming language comes with several basic data types, such as numbers, strings, or binary values. Building on these, you've got more complex types like lists (or arrays), dictionaries, maps, and objects. 47 | 48 | Imagine data stored in variables as labeled boxes. These labels help programmers keep track of what type of data is inside. As a program runs, it’s essentially moving and transforming these boxes of data through various statements and functions. 49 | 50 | Data wrangling requires a structured approach, and that's where "flow control" comes into play. It's the programming equivalent of a traffic signal, directing how tasks flow in the code. Sometimes actions run one after another (that's sequence), sometimes they repeat (loops), and sometimes they only happen under certain conditions (conditionals). 51 | 52 | In any programming language, a statement is just an instruction to do something with data. And when tasks get complex, they can be bundled into "functions" for efficiency and reuse throughout the code. 53 | 54 | As a beginner, grasp these concepts, and you're off to a solid start. And yes, being able to explain your code in plain English is a superpower in its own right! 55 | 56 | ## What is Python? 57 | 58 | Python is a programming language that is known for its simplicity, ease of use, and beginner-friendly nature. It is also widely popular in the field of artificial intelligence (AI). 59 | 60 | ## Setting up the Development Environment 61 | 62 | To set up a development environment on your computer, you can follow these steps: 63 | 64 | 1. Install Homebrew by running the following command in your terminal: 65 | 66 | ```bash 67 | /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" 68 | ``` 69 | 70 | 2. Install JupyterLab Desktop using Homebrew by running the following command in your terminal: 71 | 72 | ```bash 73 | brew install --cask jupyterlab 74 | ``` 75 | 76 | 3. Manually set up the JupyterLab command-line interface (CLI) by running the following commands in your terminal: 77 | 78 | ```bash 79 | sudo chmod 755 /Applications/JupyterLab.app/Contents/Resources/app/jlab 80 | sudo ln -s /Applications/JupyterLab.app/Contents/Resources/app/jlab /usr/local/bin/jlab 81 | ``` 82 | 83 | Once you have completed these steps, you can launch JupyterLab Desktop either by typing "Jupyter" in Spotlight and clicking on the JupyterLab Desktop icon, or by using the CLI command "jlab" in the terminal. 84 | 85 | Now you are ready to start using JupyterLab for your Python development. 86 | 87 | ## Get this tutorial to local 88 | 89 | 1. Install `git` by running the following command in your terminal: 90 | 91 | ```bash 92 | brew install git 93 | ``` 94 | 95 | 2. Clone this repo: 96 | 97 | ``` bash 98 | mkdir ~/github 99 | cd ~/github 100 | git clone .... 101 | ``` 102 | 103 | 3. Launch JupyterLab-Desktop to view notebooks: 104 | 105 | ```bash 106 | cd ~/github/... 107 | jlab . 108 | ``` 109 | -------------------------------------------------------------------------------- /cheatsheet.02.Built-in.Functions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "de059b4b", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Built-in Functions\n", 9 | "\n", 10 | "The Python interpreter has a number of functions and types built into it that are always available.\n", 11 | "\n", 12 | "## Python built-in Functions\n", 13 | "\n", 14 | "| Function | Description |\n", 15 | "| ------------------------------------------------------------ | ------------------------------------------------------------ |\n", 16 | "| [abs()](https://www.pythoncheatsheet.org/builtin/abs) | Return the absolute value of a number. |\n", 17 | "| [aiter()](https://www.pythoncheatsheet.org/builtin/aiter) | Return an asynchronous iterator for an asynchronous iterable. |\n", 18 | "| [all()](https://www.pythoncheatsheet.org/builtin/all) | Return True if all elements of the iterable are true. |\n", 19 | "| [any()](https://www.pythoncheatsheet.org/builtin/any) | Return True if any element of the iterable is true. |\n", 20 | "| [ascii()](https://www.pythoncheatsheet.org/builtin/ascii) | Return a string with a printable representation of an object. |\n", 21 | "| [bin()](https://www.pythoncheatsheet.org/builtin/bin) | Convert an integer number to a binary string. |\n", 22 | "| [bool()](https://www.pythoncheatsheet.org/builtin/bool) | Return a Boolean value. |\n", 23 | "| [breakpoint()](https://www.pythoncheatsheet.org/builtin/breakpoint) | Drops you into the debugger at the call site. |\n", 24 | "| [bytearray()](https://www.pythoncheatsheet.org/builtin/bytearray) | Return a new array of bytes. |\n", 25 | "| [bytes()](https://www.pythoncheatsheet.org/builtin/bytes) | Return a new “bytes” object. |\n", 26 | "| [callable()](https://www.pythoncheatsheet.org/builtin/callable) | Return True if the object argument is callable, False if not. |\n", 27 | "| [chr()](https://www.pythoncheatsheet.org/builtin/chr) | Return the string representing a character. |\n", 28 | "| [classmethod()](https://www.pythoncheatsheet.org/builtin/classmethod) | Transform a method into a class method. |\n", 29 | "| [compile()](https://www.pythoncheatsheet.org/builtin/compile) | Compile the source into a code or AST object. |\n", 30 | "| [complex()](https://www.pythoncheatsheet.org/builtin/complex) | Return a complex number with the value real + imag*1j. |\n", 31 | "| [delattr()](https://www.pythoncheatsheet.org/builtin/delattr) | Deletes the named attribute, provided the object allows it. |\n", 32 | "| [dict()](https://www.pythoncheatsheet.org/builtin/dict) | Create a new dictionary. |\n", 33 | "| [dir()](https://www.pythoncheatsheet.org/builtin/dir) | Return the list of names in the current local scope. |\n", 34 | "| [divmod()](https://www.pythoncheatsheet.org/builtin/divmod) | Return a pair of numbers consisting of their quotient and remainder. |\n", 35 | "| [enumerate()](https://www.pythoncheatsheet.org/builtin/enumerate) | Return an enumerate object. |\n", 36 | "| [eval()](https://www.pythoncheatsheet.org/builtin/eval) | Evaluates and executes an expression. |\n", 37 | "| [exec()](https://www.pythoncheatsheet.org/builtin/exec) | This function supports dynamic execution of Python code. |\n", 38 | "| [filter()](https://www.pythoncheatsheet.org/builtin/filter) | Construct an iterator from an iterable and returns true. |\n", 39 | "| [float()](https://www.pythoncheatsheet.org/builtin/float) | Return a floating point number from a number or string. |\n", 40 | "| [format()](https://www.pythoncheatsheet.org/builtin/format) | Convert a value to a “formatted” representation. |\n", 41 | "| [frozenset()](https://www.pythoncheatsheet.org/builtin/frozenset) | Return a new frozenset object. |\n", 42 | "| [getattr()](https://www.pythoncheatsheet.org/builtin/getattr) | Return the value of the named attribute of object. |\n", 43 | "| [globals()](https://www.pythoncheatsheet.org/builtin/globals) | Return the dictionary implementing the current module namespace. |\n", 44 | "| [hasattr()](https://www.pythoncheatsheet.org/builtin/hasattr) | True if the string is the name of one of the object’s attributes. |\n", 45 | "| [hash()](https://www.pythoncheatsheet.org/builtin/hash) | Return the hash value of the object. |\n", 46 | "| [help()](https://www.pythoncheatsheet.org/builtin/help) | Invoke the built-in help system. |\n", 47 | "| [hex()](https://www.pythoncheatsheet.org/builtin/hex) | Convert an integer number to a lowercase hexadecimal string. |\n", 48 | "| [id()](https://www.pythoncheatsheet.org/builtin/id) | Return the “identity” of an object. |\n", 49 | "| [input()](https://www.pythoncheatsheet.org/builtin/input) | This function takes an input and converts it into a string. |\n", 50 | "| [int()](https://www.pythoncheatsheet.org/builtin/int) | Return an integer object constructed from a number or string. |\n", 51 | "| [isinstance()](https://www.pythoncheatsheet.org/builtin/isinstance) | Return True if the object argument is an instance of an object. |\n", 52 | "| [issubclass()](https://www.pythoncheatsheet.org/builtin/issubclass) | Return True if class is a subclass of classinfo. |\n", 53 | "| [iter()](https://www.pythoncheatsheet.org/builtin/iter) | Return an iterator object. |\n", 54 | "| [len()](https://www.pythoncheatsheet.org/builtin/len) | Return the length (the number of items) of an object. |\n", 55 | "| [list()](https://www.pythoncheatsheet.org/builtin/list) | Rather than being a function, list is a mutable sequence type. |\n", 56 | "| [locals()](https://www.pythoncheatsheet.org/builtin/locals) | Update and return a dictionary with the current local symbol table. |\n", 57 | "| [map()](https://www.pythoncheatsheet.org/builtin/map) | Return an iterator that applies function to every item of iterable. |\n", 58 | "| [max()](https://www.pythoncheatsheet.org/builtin/max) | Return the largest item in an iterable. |\n", 59 | "| [min()](https://www.pythoncheatsheet.org/builtin/min) | Return the smallest item in an iterable. |\n", 60 | "| [next()](https://www.pythoncheatsheet.org/builtin/next) | Retrieve the next item from the iterator. |\n", 61 | "| [object()](https://www.pythoncheatsheet.org/builtin/object) | Return a new featureless object. |\n", 62 | "| [oct()](https://www.pythoncheatsheet.org/builtin/oct) | Convert an integer number to an octal string. |\n", 63 | "| [open()](https://www.pythoncheatsheet.org/builtin/open) | Open file and return a corresponding file object. |\n", 64 | "| [ord()](https://www.pythoncheatsheet.org/builtin/ord) | Return an integer representing the Unicode code point of a character. |\n", 65 | "| [pow()](https://www.pythoncheatsheet.org/builtin/pow) | Return base to the power exp. |\n", 66 | "| [print()](https://www.pythoncheatsheet.org/builtin/print) | Print objects to the text stream file. |\n", 67 | "| [property()](https://www.pythoncheatsheet.org/builtin/property) | Return a property attribute. |\n", 68 | "| [repr()](https://www.pythoncheatsheet.org/builtin/repr) | Return a string containing a printable representation of an object. |\n", 69 | "| [reversed()](https://www.pythoncheatsheet.org/builtin/reversed) | Return a reverse iterator. |\n", 70 | "| [round()](https://www.pythoncheatsheet.org/builtin/round) | Return number rounded to ndigits precision after the decimal point. |\n", 71 | "| [set()](https://www.pythoncheatsheet.org/builtin/set) | Return a new set object. |\n", 72 | "| [setattr()](https://www.pythoncheatsheet.org/builtin/setattr) | This is the counterpart of getattr(). |\n", 73 | "| [slice()](https://www.pythoncheatsheet.org/builtin/slice) | Return a sliced object representing a set of indices. |\n", 74 | "| [sorted()](https://www.pythoncheatsheet.org/builtin/sorted) | Return a new sorted list from the items in iterable. |\n", 75 | "| [staticmethod()](https://www.pythoncheatsheet.org/builtin/staticmethod) | Transform a method into a static method. |\n", 76 | "| [str()](https://www.pythoncheatsheet.org/builtin/str) | Return a str version of object. |\n", 77 | "| [sum()](https://www.pythoncheatsheet.org/builtin/sum) | Sums start and the items of an iterable. |\n", 78 | "| [super()](https://www.pythoncheatsheet.org/builtin/super) | Return a proxy object that delegates method calls to a parent or sibling. |\n", 79 | "| [tuple()](https://www.pythoncheatsheet.org/builtin/tuple) | Rather than being a function, is actually an immutable sequence type. |\n", 80 | "| [type()](https://www.pythoncheatsheet.org/builtin/type) | Return the type of an object. |\n", 81 | "| [vars()](https://www.pythoncheatsheet.org/builtin/vars) | Return the dict attribute for any other object with a dict attribute. |\n", 82 | "| [zip()](https://www.pythoncheatsheet.org/builtin/zip) | Iterate over several iterables in parallel. |\n", 83 | "| [**import**()](https://www.pythoncheatsheet.org/builtin/import) | This function is invoked by the import statement. |" 84 | ] 85 | } 86 | ], 87 | "metadata": { 88 | "kernelspec": { 89 | "display_name": "Python 3 (ipykernel)", 90 | "language": "python", 91 | "name": "python3" 92 | }, 93 | "language_info": { 94 | "codemirror_mode": { 95 | "name": "ipython", 96 | "version": 3 97 | }, 98 | "file_extension": ".py", 99 | "mimetype": "text/x-python", 100 | "name": "python", 101 | "nbconvert_exporter": "python", 102 | "pygments_lexer": "ipython3", 103 | "version": "3.12.0" 104 | } 105 | }, 106 | "nbformat": 4, 107 | "nbformat_minor": 5 108 | } 109 | -------------------------------------------------------------------------------- /cheatsheet.04.Functions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "14398258", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Functions\n", 9 | "\n", 10 | "wikiversity link: [Programming Functions](https://en.wikiversity.org/wiki/Programming_Fundamentals/Functions)\n", 11 | "\n", 12 | "A function is a block of organized code that is used to perform a single task. They provide better modularity for your application and reuse-ability.\n", 13 | "\n", 14 | "## Function Arguments\n", 15 | "\n", 16 | "A function can take `arguments` and `return values`:\n", 17 | "\n", 18 | "In the following example, the function **say_hello** receives the argument “name” and prints a greeting:" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "id": "bfe4b94c-f5f4-47f7-a586-fd2a37e9384f", 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "def say_hello(name):\n", 29 | " print(f'Hello {name}')" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "id": "33809b23-f57d-491f-aaa0-26ad6e83e11c", 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "say_hello('Carlos')\n", 40 | "# Hello Carlos" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "id": "2930f855-5989-4e7d-915a-ab355fdfc628", 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "say_hello('Wanda')\n", 51 | "# Hello Wanda" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "id": "9cf2f727-7d0b-4a10-ab6c-887d8c551bc0", 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "say_hello('Rose')\n", 62 | "# Hello Rose" 63 | ] 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "id": "fff0cabd", 68 | "metadata": {}, 69 | "source": [ 70 | "## Keyword Arguments\n", 71 | "\n", 72 | "To improve code readability, we should be as explicit as possible. We can achieve this in our functions by using `Keyword Arguments`:" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": null, 78 | "id": "1086ecdd-ba8c-4bb6-af44-a50abc684ce0", 79 | "metadata": {}, 80 | "outputs": [], 81 | "source": [ 82 | "def say_hi(name, greeting):\n", 83 | " print(f\"{greeting} {name}\")" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": null, 89 | "id": "04f25d36-32df-44c7-836e-90ba1e2bf3d8", 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [ 93 | "# without keyword arguments\n", 94 | "say_hi('John', 'Hello')\n", 95 | "# Hello John" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "id": "68faa3b9-845d-4493-bb31-b3da8fb5ccde", 102 | "metadata": {}, 103 | "outputs": [], 104 | "source": [ 105 | "# with keyword arguments\n", 106 | "say_hi(name='Anna', greeting='Hi')\n", 107 | "# Hi Anna" 108 | ] 109 | }, 110 | { 111 | "cell_type": "markdown", 112 | "id": "e750866d", 113 | "metadata": {}, 114 | "source": [ 115 | "## Return Values\n", 116 | "\n", 117 | "When creating a function using the `def` statement, you can specify what the return value should be with a `return` statement. A return statement consists of the following:\n", 118 | "\n", 119 | "- The `return` keyword.\n", 120 | "- The value or expression that the function should return." 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "id": "0a6d3640", 127 | "metadata": {}, 128 | "outputs": [], 129 | "source": [ 130 | "def sum_two_numbers(number_1, number_2):\n", 131 | " return number_1 + number_2\n", 132 | "\n", 133 | "result = sum_two_numbers(7, 8)\n", 134 | "print(result)\n", 135 | "# 15" 136 | ] 137 | }, 138 | { 139 | "cell_type": "markdown", 140 | "id": "9919a8ed", 141 | "metadata": {}, 142 | "source": [ 143 | "## Local and Global Scope\n", 144 | "\n", 145 | "- Code in the global scope cannot use any local variables.\n", 146 | "- However, a local scope can access global variables.\n", 147 | "- Code in a function’s local scope cannot use variables in any other local scope.\n", 148 | "- You can use the same name for different variables if they are in different scopes. That is, there can be a local variable named spam and a global variable also named spam." 149 | ] 150 | }, 151 | { 152 | "cell_type": "code", 153 | "execution_count": null, 154 | "id": "7dd7e955", 155 | "metadata": {}, 156 | "outputs": [], 157 | "source": [ 158 | "global_variable = 'I am available everywhere'\n", 159 | "\n", 160 | "def some_function():\n", 161 | " print(global_variable) # because is global\n", 162 | " local_variable = \"only available within this function\"\n", 163 | "\n", 164 | "print(local_variable)\n", 165 | "\n", 166 | "# the following code will throw error because\n", 167 | "# 'local_variable' only exists inside 'some_function'\n", 168 | "print(local_variable)\n", 169 | "# Traceback (most recent call last):\n", 170 | "# File \"\", line 10, in \n", 171 | "# NameError: name 'local_variable' is not defined" 172 | ] 173 | }, 174 | { 175 | "cell_type": "markdown", 176 | "id": "0129e985", 177 | "metadata": {}, 178 | "source": [ 179 | "## The global Statement\n", 180 | "\n", 181 | "If you need to modify a global variable from within a function, use the global statement:" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": null, 187 | "id": "3cc34f15", 188 | "metadata": {}, 189 | "outputs": [], 190 | "source": [ 191 | "def spam():\n", 192 | " global eggs\n", 193 | " eggs = 'spam'\n", 194 | "\n", 195 | "eggs = 'global'\n", 196 | "spam()\n", 197 | "print(eggs)" 198 | ] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "id": "497bb40a", 203 | "metadata": {}, 204 | "source": [ 205 | "There are four rules to tell whether a variable is in a local scope or global scope:\n", 206 | "\n", 207 | "1. If a variable is being used in the global scope (that is, outside all functions), then it is always a global variable.\n", 208 | "2. If there is a global statement for that variable in a function, it is a global variable.\n", 209 | "3. Otherwise, if the variable is used in an assignment statement in the function, it is a local variable.\n", 210 | "4. But if the variable is not used in an assignment statement, it is a global variable.\n", 211 | "\n", 212 | "## Lambda Functions\n", 213 | "\n", 214 | "In Python, a lambda function is a single-line, anonymous function, which can have any number of arguments, but it can only have one expression.\n", 215 | "\n", 216 | "\n", 217 | "\n", 218 | "From the [Python 3 Tutorial](https://docs.python.org/3/library/ast.html?highlight=lambda#function-and-class-definitions)\n", 219 | "\n", 220 | "lambda is a minimal function definition that can be used inside an expression. Unlike FunctionDef, body holds a single node.\n", 221 | "\n", 222 | "\n", 223 | "\n", 224 | "Single line expression\n", 225 | "\n", 226 | "Lambda functions can only evaluate an expression, like a single line of code.\n", 227 | "\n", 228 | "This function:" 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "execution_count": null, 234 | "id": "9f7ad0ee", 235 | "metadata": {}, 236 | "outputs": [], 237 | "source": [ 238 | "def add(x, y):\n", 239 | "return x + y\n", 240 | "...\n", 241 | "add(5, 3)\n", 242 | "# 8" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "id": "c8efd681", 248 | "metadata": {}, 249 | "source": [ 250 | "Is equivalent to the *lambda* function:" 251 | ] 252 | }, 253 | { 254 | "cell_type": "code", 255 | "execution_count": null, 256 | "id": "33d5b515", 257 | "metadata": {}, 258 | "outputs": [], 259 | "source": [ 260 | "add = lambda x, y: x + y\n", 261 | "add(5, 3)\n", 262 | "# 8" 263 | ] 264 | }, 265 | { 266 | "cell_type": "markdown", 267 | "id": "acfe5713", 268 | "metadata": {}, 269 | "source": [ 270 | "Like regular nested functions, lambdas also work as lexical closures:" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": null, 276 | "id": "5fc73c7b-8d15-4da3-b53b-fcb604ef79fb", 277 | "metadata": {}, 278 | "outputs": [], 279 | "source": [ 280 | "def make_adder(n):\n", 281 | " return lambda x: x + n" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": null, 287 | "id": "6668cf16-2604-4426-a100-1ca67bef21f0", 288 | "metadata": {}, 289 | "outputs": [], 290 | "source": [ 291 | "plus_3 = make_adder(3)\n", 292 | "plus_5 = make_adder(5)" 293 | ] 294 | }, 295 | { 296 | "cell_type": "code", 297 | "execution_count": null, 298 | "id": "72b7a6a2-6e18-4a97-9962-1bc116ff92a5", 299 | "metadata": {}, 300 | "outputs": [], 301 | "source": [ 302 | "plus_3(4)\n", 303 | "# 7" 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": null, 309 | "id": "469f1403-c891-4ec7-8e7d-48c45c2ba9aa", 310 | "metadata": {}, 311 | "outputs": [], 312 | "source": [ 313 | "plus_5(4)\n", 314 | "# 9" 315 | ] 316 | } 317 | ], 318 | "metadata": { 319 | "kernelspec": { 320 | "display_name": "Python 3 (ipykernel)", 321 | "language": "python", 322 | "name": "python3" 323 | }, 324 | "language_info": { 325 | "codemirror_mode": { 326 | "name": "ipython", 327 | "version": 3 328 | }, 329 | "file_extension": ".py", 330 | "mimetype": "text/x-python", 331 | "name": "python", 332 | "nbconvert_exporter": "python", 333 | "pygments_lexer": "ipython3", 334 | "version": "3.12.0" 335 | } 336 | }, 337 | "nbformat": 4, 338 | "nbformat_minor": 5 339 | } 340 | -------------------------------------------------------------------------------- /cheatsheet.06.Dictionaries.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "c4c69b0f", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Dictionaries\n", 9 | "\n", 10 | "In Python, a dictionary is an *ordered* (from Python > 3.7) collection of `key`: `value` pairs.\n", 11 | "\n", 12 | "From the Python 3 [documentation](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)\n", 13 | "\n", 14 | "The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with `del`.\n", 15 | "\n", 16 | "Example Dictionary:" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "id": "40726513", 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "my_cat = {\n", 27 | " 'size': 'fat',\n", 28 | " 'color': 'gray',\n", 29 | " 'disposition': 'loud'\n", 30 | "}" 31 | ] 32 | }, 33 | { 34 | "cell_type": "markdown", 35 | "id": "e62c8974", 36 | "metadata": {}, 37 | "source": [ 38 | "## Set key, value using subscript operator `[]`" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": null, 44 | "id": "7af8a848", 45 | "metadata": {}, 46 | "outputs": [], 47 | "source": [ 48 | "my_cat = {\n", 49 | " 'size': 'fat',\n", 50 | " 'color': 'gray',\n", 51 | " 'disposition': 'loud',\n", 52 | "}\n", 53 | "my_cat['age_years'] = 2\n", 54 | "print(my_cat)\n", 55 | "# {'size': 'fat', 'color': 'gray', 'disposition': 'loud', 'age_years': 2}" 56 | ] 57 | }, 58 | { 59 | "cell_type": "markdown", 60 | "id": "08304bf5", 61 | "metadata": {}, 62 | "source": [ 63 | "## Get value using subscript operator `[]`\n", 64 | "\n", 65 | "In case the key is not present in dictionary [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError) is raised." 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": null, 71 | "id": "945801fb-82cb-422e-adc1-76d011692fdf", 72 | "metadata": {}, 73 | "outputs": [], 74 | "source": [ 75 | "my_cat = {\n", 76 | " 'size': 'fat',\n", 77 | " 'color': 'gray',\n", 78 | " 'disposition': 'loud',\n", 79 | "}" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": null, 85 | "id": "b2b58700-6c1d-4879-9239-f27fc7378b69", 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "print(my_cat['size'])\n", 90 | "# fat" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": null, 96 | "id": "46870832-9aef-481d-8399-9daaea5297b3", 97 | "metadata": {}, 98 | "outputs": [], 99 | "source": [ 100 | "print(my_cat['eye_color'])\n", 101 | "# Traceback (most recent call last):\n", 102 | "# File \"\", line 1, in \n", 103 | "# KeyError: 'eye_color'" 104 | ] 105 | }, 106 | { 107 | "cell_type": "markdown", 108 | "id": "9b0a85be", 109 | "metadata": {}, 110 | "source": [ 111 | "## values()\n", 112 | "\n", 113 | "The `values()` method gets the **values** of the dictionary:" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": null, 119 | "id": "77253042", 120 | "metadata": {}, 121 | "outputs": [], 122 | "source": [ 123 | "pet = {'color': 'red', 'age': 42}\n", 124 | "for value in pet.values():\n", 125 | " print(value)\n", 126 | "\n", 127 | "# red\n", 128 | "# 42" 129 | ] 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "id": "dde124c7", 134 | "metadata": {}, 135 | "source": [ 136 | "## keys()\n", 137 | "\n", 138 | "The `keys()` method gets the **keys** of the dictionary:" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": null, 144 | "id": "f385ed3e", 145 | "metadata": {}, 146 | "outputs": [], 147 | "source": [ 148 | "pet = {'color': 'red', 'age': 42}\n", 149 | "for key in pet.keys():\n", 150 | " print(key)\n", 151 | "\n", 152 | "# color\n", 153 | "# age" 154 | ] 155 | }, 156 | { 157 | "cell_type": "markdown", 158 | "id": "e3ea0fd5", 159 | "metadata": {}, 160 | "source": [ 161 | "There is no need to use **.keys()** since by default you will loop through keys:" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "id": "0e8107d4", 168 | "metadata": {}, 169 | "outputs": [], 170 | "source": [ 171 | "pet = {'color': 'red', 'age': 42}\n", 172 | "for key in pet:\n", 173 | " print(key)\n", 174 | "\n", 175 | "# color\n", 176 | "# age" 177 | ] 178 | }, 179 | { 180 | "cell_type": "markdown", 181 | "id": "dde05679", 182 | "metadata": {}, 183 | "source": [ 184 | "## items()\n", 185 | "\n", 186 | "The `items()` method gets the **items** of a dictionary and returns them as a [Tuple](https://www.pythoncheatsheet.org/cheatsheet/lists-and-tuples#the-tuple-data-type):" 187 | ] 188 | }, 189 | { 190 | "cell_type": "code", 191 | "execution_count": null, 192 | "id": "28e6c06d", 193 | "metadata": {}, 194 | "outputs": [], 195 | "source": [ 196 | "pet = {'color': 'red', 'age': 42}\n", 197 | "for item in pet.items():\n", 198 | " print(item)\n", 199 | "\n", 200 | "# ('color', 'red')\n", 201 | "# ('age', 42)" 202 | ] 203 | }, 204 | { 205 | "cell_type": "markdown", 206 | "id": "d832c8ca", 207 | "metadata": {}, 208 | "source": [ 209 | "Using the `keys()`, `values()`, and `items()` methods, a for loop can iterate over the keys, values, or key-value pairs in a dictionary, respectively." 210 | ] 211 | }, 212 | { 213 | "cell_type": "code", 214 | "execution_count": null, 215 | "id": "e703e9e2", 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [ 219 | "pet = {'color': 'red', 'age': 42}\n", 220 | "for key, value in pet.items():\n", 221 | " print(f'Key: {key} Value: {value}')\n", 222 | "\n", 223 | "# Key: color Value: red\n", 224 | "# Key: age Value: 42" 225 | ] 226 | }, 227 | { 228 | "cell_type": "markdown", 229 | "id": "01128636", 230 | "metadata": {}, 231 | "source": [ 232 | "## get()\n", 233 | "\n", 234 | "The `get()` method returns the value of an item with the given key. If the key doesn’t exist, it returns `None`:" 235 | ] 236 | }, 237 | { 238 | "cell_type": "code", 239 | "execution_count": null, 240 | "id": "c2157e2b-e2a5-44fa-8782-9b7354a0ca7a", 241 | "metadata": {}, 242 | "outputs": [], 243 | "source": [ 244 | "wife = {'name': 'Rose', 'age': 33}" 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "execution_count": null, 250 | "id": "b7bf28b1-c113-4b46-a225-50273c36f363", 251 | "metadata": {}, 252 | "outputs": [], 253 | "source": [ 254 | "f'My wife name is {wife.get(\"name\")}'\n", 255 | "# 'My wife name is Rose'" 256 | ] 257 | }, 258 | { 259 | "cell_type": "code", 260 | "execution_count": null, 261 | "id": "e5a1daf5-8fb1-4243-9727-daf1d6a93039", 262 | "metadata": {}, 263 | "outputs": [], 264 | "source": [ 265 | "f'She is {wife.get(\"age\")} years old.'\n", 266 | "# 'She is 33 years old.'" 267 | ] 268 | }, 269 | { 270 | "cell_type": "code", 271 | "execution_count": null, 272 | "id": "c2b9c08e-301a-436c-b389-fb17bb612a65", 273 | "metadata": {}, 274 | "outputs": [], 275 | "source": [ 276 | "f'She is deeply in love with {wife.get(\"husband\")}'\n", 277 | "# 'She is deeply in love with None'" 278 | ] 279 | }, 280 | { 281 | "cell_type": "markdown", 282 | "id": "ca34e919", 283 | "metadata": {}, 284 | "source": [ 285 | "You can also change the default `None` value to one of your choice:" 286 | ] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "execution_count": null, 291 | "id": "8aae4b9f", 292 | "metadata": {}, 293 | "outputs": [], 294 | "source": [ 295 | "wife = {'name': 'Rose', 'age': 33}\n", 296 | "\n", 297 | "f'She is deeply in love with {wife.get(\"husband\", \"lover\")}'\n", 298 | "# 'She is deeply in love with lover'" 299 | ] 300 | }, 301 | { 302 | "cell_type": "markdown", 303 | "id": "d5648277", 304 | "metadata": {}, 305 | "source": [ 306 | "## Adding items with setdefault()\n", 307 | "\n", 308 | "It’s possible to add an item to a dictionary in this way:" 309 | ] 310 | }, 311 | { 312 | "cell_type": "code", 313 | "execution_count": null, 314 | "id": "2c18e284-9ffc-4df5-88f3-0fff0f72a3f1", 315 | "metadata": {}, 316 | "outputs": [], 317 | "source": [ 318 | "wife = {'name': 'Rose', 'age': 33}\n", 319 | "wife\n", 320 | "\n", 321 | "# {'name': 'Rose', 'age': 33}" 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": null, 327 | "id": "398056da-38a3-49d0-8f33-f530ba7fcd80", 328 | "metadata": {}, 329 | "outputs": [], 330 | "source": [ 331 | "if 'has_hair' not in wife:\n", 332 | " wife['has_hair'] = True\n", 333 | "wife\n", 334 | "\n", 335 | "# {'name': 'Rose', 'age': 33, 'has_hair': True}" 336 | ] 337 | }, 338 | { 339 | "cell_type": "markdown", 340 | "id": "54f7c608", 341 | "metadata": {}, 342 | "source": [ 343 | "Using the `setdefault` method, we can make the same code more short:" 344 | ] 345 | }, 346 | { 347 | "cell_type": "code", 348 | "execution_count": null, 349 | "id": "1d710a23", 350 | "metadata": {}, 351 | "outputs": [], 352 | "source": [ 353 | "wife = {'name': 'Rose', 'age': 33}\n", 354 | "wife.setdefault('has_hair', True)\n", 355 | "wife\n", 356 | "# {'name': 'Rose', 'age': 33, 'has_hair': True}" 357 | ] 358 | }, 359 | { 360 | "cell_type": "markdown", 361 | "id": "2734af93", 362 | "metadata": {}, 363 | "source": [ 364 | "## Removing Items\n", 365 | "\n", 366 | "### pop()\n", 367 | "\n", 368 | "The `pop()` method removes and returns an item based on a given key." 369 | ] 370 | }, 371 | { 372 | "cell_type": "code", 373 | "execution_count": null, 374 | "id": "3a31a7c5-ddae-424e-974f-17476e213f1a", 375 | "metadata": {}, 376 | "outputs": [], 377 | "source": [ 378 | "wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}" 379 | ] 380 | }, 381 | { 382 | "cell_type": "code", 383 | "execution_count": null, 384 | "id": "aff37d6a-3c49-421b-ae9b-9dc3d88ee977", 385 | "metadata": {}, 386 | "outputs": [], 387 | "source": [ 388 | "wife.pop('age')\n", 389 | "# 33" 390 | ] 391 | }, 392 | { 393 | "cell_type": "code", 394 | "execution_count": null, 395 | "id": "19d6f2ef-b240-476b-8541-caf0130c8d83", 396 | "metadata": {}, 397 | "outputs": [], 398 | "source": [ 399 | "wife\n", 400 | "# {'name': 'Rose', 'hair': 'brown'}" 401 | ] 402 | }, 403 | { 404 | "cell_type": "markdown", 405 | "id": "995ac965", 406 | "metadata": {}, 407 | "source": [ 408 | "### popitem()\n", 409 | "\n", 410 | "The `popitem()` method removes the last item in a dictionary and returns it." 411 | ] 412 | }, 413 | { 414 | "cell_type": "code", 415 | "execution_count": null, 416 | "id": "4a34efb7-78c8-4a68-9dfc-20f2749e9e84", 417 | "metadata": {}, 418 | "outputs": [], 419 | "source": [ 420 | "wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}" 421 | ] 422 | }, 423 | { 424 | "cell_type": "code", 425 | "execution_count": null, 426 | "id": "e9926ad9-ebca-42e9-9989-6ccb94e24f30", 427 | "metadata": {}, 428 | "outputs": [], 429 | "source": [ 430 | "wife.popitem()\n", 431 | "# ('hair', 'brown')" 432 | ] 433 | }, 434 | { 435 | "cell_type": "code", 436 | "execution_count": null, 437 | "id": "a8015574-24b6-4d27-9a65-aefae5925d09", 438 | "metadata": {}, 439 | "outputs": [], 440 | "source": [ 441 | "wife\n", 442 | "# {'name': 'Rose', 'age': 33}" 443 | ] 444 | }, 445 | { 446 | "cell_type": "markdown", 447 | "id": "e41f903a", 448 | "metadata": {}, 449 | "source": [ 450 | "### del()\n", 451 | "\n", 452 | "The `del()` method removes an item based on a given key." 453 | ] 454 | }, 455 | { 456 | "cell_type": "code", 457 | "execution_count": null, 458 | "id": "7ae4a9b6-cdfe-4c32-a787-e86b179f78d1", 459 | "metadata": {}, 460 | "outputs": [], 461 | "source": [ 462 | "wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}" 463 | ] 464 | }, 465 | { 466 | "cell_type": "code", 467 | "execution_count": null, 468 | "id": "6521ed91-4c60-4513-9cc7-b4d2d68655da", 469 | "metadata": {}, 470 | "outputs": [], 471 | "source": [ 472 | "del wife['age']\n", 473 | "wife\n", 474 | "# {'name': 'Rose', 'hair': 'brown'}" 475 | ] 476 | }, 477 | { 478 | "cell_type": "markdown", 479 | "id": "f3250f36", 480 | "metadata": {}, 481 | "source": [ 482 | "### clear()\n", 483 | "\n", 484 | "The`clear()` method removes all the items in a dictionary." 485 | ] 486 | }, 487 | { 488 | "cell_type": "code", 489 | "execution_count": null, 490 | "id": "772d5552", 491 | "metadata": {}, 492 | "outputs": [], 493 | "source": [ 494 | "wife = {'name': 'Rose', 'age': 33, 'hair': 'brown'}\n", 495 | "wife.clear()\n", 496 | "wife\n", 497 | "# {}" 498 | ] 499 | }, 500 | { 501 | "cell_type": "markdown", 502 | "id": "428f778a", 503 | "metadata": {}, 504 | "source": [ 505 | "## Checking keys in a Dictionary" 506 | ] 507 | }, 508 | { 509 | "cell_type": "code", 510 | "execution_count": null, 511 | "id": "acba4629-e2e6-4e2a-baac-4a29109db0f3", 512 | "metadata": {}, 513 | "outputs": [], 514 | "source": [ 515 | "person = {'name': 'Rose', 'age': 33}" 516 | ] 517 | }, 518 | { 519 | "cell_type": "code", 520 | "execution_count": null, 521 | "id": "74e4dd75-b6f7-464a-958a-bee2424b1889", 522 | "metadata": {}, 523 | "outputs": [], 524 | "source": [ 525 | "'name' in person.keys()\n", 526 | "# True" 527 | ] 528 | }, 529 | { 530 | "cell_type": "code", 531 | "execution_count": null, 532 | "id": "3d0a4886-18ef-4e8b-82ce-0f842e8ba0fa", 533 | "metadata": {}, 534 | "outputs": [], 535 | "source": [ 536 | "'height' in person.keys()\n", 537 | "# False" 538 | ] 539 | }, 540 | { 541 | "cell_type": "code", 542 | "execution_count": null, 543 | "id": "17deed29-6ab4-4704-92c8-fdb76e59e43e", 544 | "metadata": {}, 545 | "outputs": [], 546 | "source": [ 547 | "'skin' in person # You can omit keys()\n", 548 | "# False" 549 | ] 550 | }, 551 | { 552 | "cell_type": "markdown", 553 | "id": "bb9c3e73", 554 | "metadata": {}, 555 | "source": [ 556 | "## Checking values in a Dictionary" 557 | ] 558 | }, 559 | { 560 | "cell_type": "code", 561 | "execution_count": null, 562 | "id": "1d919ffc-a518-4935-a606-7befbd1479a9", 563 | "metadata": {}, 564 | "outputs": [], 565 | "source": [ 566 | "person = {'name': 'Rose', 'age': 33}" 567 | ] 568 | }, 569 | { 570 | "cell_type": "code", 571 | "execution_count": null, 572 | "id": "decc2cfb-8e97-4d7c-83ce-a87adf20c771", 573 | "metadata": {}, 574 | "outputs": [], 575 | "source": [ 576 | "'Rose' in person.values()\n", 577 | "# True" 578 | ] 579 | }, 580 | { 581 | "cell_type": "code", 582 | "execution_count": null, 583 | "id": "ffb54833-fc84-4257-97cd-8363b45731d9", 584 | "metadata": {}, 585 | "outputs": [], 586 | "source": [ 587 | "33 in person.values()\n", 588 | "# True" 589 | ] 590 | }, 591 | { 592 | "cell_type": "markdown", 593 | "id": "2a89286a", 594 | "metadata": {}, 595 | "source": [ 596 | "## Pretty Printing" 597 | ] 598 | }, 599 | { 600 | "cell_type": "code", 601 | "execution_count": null, 602 | "id": "d2dd92bb", 603 | "metadata": {}, 604 | "outputs": [], 605 | "source": [ 606 | "import pprint\n", 607 | "\n", 608 | "wife = {'name': 'Rose', 'age': 33, 'has_hair': True, 'hair_color': 'brown', 'height': 1.6, 'eye_color': 'brown'}\n", 609 | "pprint.pprint(wife)\n", 610 | "# {'age': 33,\n", 611 | "# 'eye_color': 'brown',\n", 612 | "# 'hair_color': 'brown',\n", 613 | "# 'has_hair': True,\n", 614 | "# 'height': 1.6,\n", 615 | "# 'name': 'Rose'}" 616 | ] 617 | }, 618 | { 619 | "cell_type": "markdown", 620 | "id": "1de8a070", 621 | "metadata": {}, 622 | "source": [ 623 | "## Merge two dictionaries\n", 624 | "\n", 625 | "For Python 3.5+:\n" 626 | ] 627 | }, 628 | { 629 | "cell_type": "code", 630 | "execution_count": null, 631 | "id": "8086abda-b085-4180-84e7-3534c38422c5", 632 | "metadata": {}, 633 | "outputs": [], 634 | "source": [ 635 | "dict_a = {'a': 1, 'b': 2}\n", 636 | "dict_b = {'b': 3, 'c': 4}\n", 637 | "dict_c = {**dict_a, **dict_b}\n", 638 | "dict_c\n", 639 | "# {'a': 1, 'b': 3, 'c': 4}" 640 | ] 641 | } 642 | ], 643 | "metadata": { 644 | "kernelspec": { 645 | "display_name": "Python 3 (ipykernel)", 646 | "language": "python", 647 | "name": "python3" 648 | }, 649 | "language_info": { 650 | "codemirror_mode": { 651 | "name": "ipython", 652 | "version": 3 653 | }, 654 | "file_extension": ".py", 655 | "mimetype": "text/x-python", 656 | "name": "python", 657 | "nbconvert_exporter": "python", 658 | "pygments_lexer": "ipython3", 659 | "version": "3.12.0" 660 | } 661 | }, 662 | "nbformat": 4, 663 | "nbformat_minor": 5 664 | } 665 | -------------------------------------------------------------------------------- /cheatsheet.07.Sets.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "39ab8dac", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Sets\n", 9 | "\n", 10 | "Python comes equipped with several built-in data types to help us organize our data. These structures include lists, dictionaries, tuples and **sets**.\n", 11 | "\n", 12 | "From the Python 3 [documentation](https://docs.python.org/3/tutorial/datastructures.html#sets)\n", 13 | "\n", 14 | "A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries.\n", 15 | "\n", 16 | "Read [Python Sets: What, Why and How](https://www.pythoncheatsheet.org/blog/python-sets-what-why-how) for a more in-deep reference.\n", 17 | "\n", 18 | "## Initializing a set\n", 19 | "\n", 20 | "There are two ways to create sets: using curly braces `{}` and the built-in function `set()`\n", 21 | "\n", 22 | "Empty Sets\n", 23 | "\n", 24 | "When creating set, be sure to not use empty curly braces `{}` or you will get an empty dictionary instead." 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "id": "c004dbd3", 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "s = {1, 2, 3}\n", 35 | "s = set([1, 2, 3])\n", 36 | "\n", 37 | "s = {} # this will create a dictionary instead of a set\n", 38 | "type(s)\n", 39 | "# " 40 | ] 41 | }, 42 | { 43 | "cell_type": "markdown", 44 | "id": "c1c28a39", 45 | "metadata": {}, 46 | "source": [ 47 | "## Unordered collections of unique elements\n", 48 | "\n", 49 | "A set automatically remove all the duplicate values." 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": null, 55 | "id": "4076e4d0", 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "s = {1, 2, 3, 2, 3, 4}\n", 60 | "s\n", 61 | "# {1, 2, 3, 4}" 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "id": "1bcf2125", 67 | "metadata": {}, 68 | "source": [ 69 | "And as an unordered data type, they can’t be indexed." 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": null, 75 | "id": "2390aa64", 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "s = {1, 2, 3}\n", 80 | "s[0]\n", 81 | "# Traceback (most recent call last):\n", 82 | "# File \"\", line 1, in \n", 83 | "# TypeError: 'set' object does not support indexing" 84 | ] 85 | }, 86 | { 87 | "cell_type": "markdown", 88 | "id": "85fb2d7e", 89 | "metadata": {}, 90 | "source": [ 91 | "## set add() and update()\n", 92 | "\n", 93 | "Using the `add()` method we can add a single element to the set." 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "id": "be664c5d", 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [ 103 | "s = {1, 2, 3}\n", 104 | "s.add(4)\n", 105 | "s\n", 106 | "# {1, 2, 3, 4}" 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "id": "52c3da0e", 112 | "metadata": {}, 113 | "source": [ 114 | "And with `update()`, multiple ones:" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "id": "f32450c7", 121 | "metadata": {}, 122 | "outputs": [], 123 | "source": [ 124 | "s = {1, 2, 3}\n", 125 | "s.update([2, 3, 4, 5, 6])\n", 126 | "s\n", 127 | "# {1, 2, 3, 4, 5, 6}" 128 | ] 129 | }, 130 | { 131 | "cell_type": "markdown", 132 | "id": "e5fe48e6", 133 | "metadata": {}, 134 | "source": [ 135 | "## set remove() and discard()\n", 136 | "\n", 137 | "Both methods will remove an element from the set, but `remove()` will raise a `key error` if the value doesn’t exist." 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "id": "85198970-580b-47da-94d4-a922db60b8bc", 144 | "metadata": {}, 145 | "outputs": [], 146 | "source": [ 147 | "s = {1, 2, 3}\n", 148 | "s.remove(3)\n", 149 | "s\n", 150 | "# {1, 2}" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "id": "3fb66ddc-bfc2-49d5-9607-f2708bdccdb3", 157 | "metadata": {}, 158 | "outputs": [], 159 | "source": [ 160 | "s.remove(3)\n", 161 | "# Traceback (most recent call last):\n", 162 | "# File \"\", line 1, in \n", 163 | "# KeyError: 3" 164 | ] 165 | }, 166 | { 167 | "cell_type": "markdown", 168 | "id": "54f04058", 169 | "metadata": {}, 170 | "source": [ 171 | "`discard()` won’t raise any errors." 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": null, 177 | "id": "b1c46000-c56e-42f6-8ffa-0aeefde6031b", 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "s = {1, 2, 3}\n", 182 | "s.discard(3)\n", 183 | "s\n", 184 | "# {1, 2}" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": null, 190 | "id": "59fb1bff-8a0f-4fcd-9e2b-95c4a54f5e78", 191 | "metadata": {}, 192 | "outputs": [], 193 | "source": [ 194 | "s.discard(3)\n", 195 | "# won't raise any errors." 196 | ] 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "id": "a8d161e8", 201 | "metadata": {}, 202 | "source": [ 203 | "## set union()\n", 204 | "\n", 205 | "`union()` or `|` will create a new set with all the elements from the sets provided." 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "id": "7ebc725c", 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [ 215 | "s1 = {1, 2, 3}\n", 216 | "s2 = {3, 4, 5}\n", 217 | "s1.union(s2) # or 's1 | s2'\n", 218 | "# {1, 2, 3, 4, 5}" 219 | ] 220 | }, 221 | { 222 | "cell_type": "markdown", 223 | "id": "0599f573", 224 | "metadata": {}, 225 | "source": [ 226 | "## set intersection\n", 227 | "\n", 228 | "`intersection` or `&` will return a set with only the elements that are common to all of them." 229 | ] 230 | }, 231 | { 232 | "cell_type": "code", 233 | "execution_count": null, 234 | "id": "20afb0c6", 235 | "metadata": {}, 236 | "outputs": [], 237 | "source": [ 238 | "s1 = {1, 2, 3}\n", 239 | "s2 = {2, 3, 4}\n", 240 | "s3 = {3, 4, 5}\n", 241 | "s1.intersection(s2, s3) # or 's1 & s2 & s3'\n", 242 | "# {3}" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "id": "c1617042", 248 | "metadata": {}, 249 | "source": [ 250 | "## set difference\n", 251 | "\n", 252 | "`difference` or `-` will return only the elements that are unique to the first set (invoked set)." 253 | ] 254 | }, 255 | { 256 | "cell_type": "code", 257 | "execution_count": null, 258 | "id": "9e768482-174b-432c-a113-728a3080d3a7", 259 | "metadata": {}, 260 | "outputs": [], 261 | "source": [ 262 | "s1 = {1, 2, 3}\n", 263 | "s2 = {2, 3, 4}" 264 | ] 265 | }, 266 | { 267 | "cell_type": "code", 268 | "execution_count": null, 269 | "id": "f342ca3e-1455-4a08-aaa2-7e7f34b6b6e7", 270 | "metadata": {}, 271 | "outputs": [], 272 | "source": [ 273 | "s1.difference(s2) # or 's1 - s2'\n", 274 | "# {1}" 275 | ] 276 | }, 277 | { 278 | "cell_type": "code", 279 | "execution_count": null, 280 | "id": "af795ff3-00fe-4f6f-a6f0-af55daef958a", 281 | "metadata": {}, 282 | "outputs": [], 283 | "source": [ 284 | "s2.difference(s1) # or 's2 - s1'\n", 285 | "# {4}" 286 | ] 287 | }, 288 | { 289 | "cell_type": "markdown", 290 | "id": "72684673", 291 | "metadata": {}, 292 | "source": [ 293 | "## set symetric_difference\n", 294 | "\n", 295 | "`symetric_difference` or `^` will return all the elements that are not common between them.\n" 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": null, 301 | "id": "04f116b9-e62c-4fb3-9467-14d52f95917f", 302 | "metadata": {}, 303 | "outputs": [], 304 | "source": [ 305 | "s1 = {1, 2, 3}\n", 306 | "s2 = {2, 3, 4}\n", 307 | "s1.symmetric_difference(s2) # or 's1 ^ s2'\n", 308 | "# {1, 4}" 309 | ] 310 | } 311 | ], 312 | "metadata": { 313 | "kernelspec": { 314 | "display_name": "Python 3 (ipykernel)", 315 | "language": "python", 316 | "name": "python3" 317 | }, 318 | "language_info": { 319 | "codemirror_mode": { 320 | "name": "ipython", 321 | "version": 3 322 | }, 323 | "file_extension": ".py", 324 | "mimetype": "text/x-python", 325 | "name": "python", 326 | "nbconvert_exporter": "python", 327 | "pygments_lexer": "ipython3", 328 | "version": "3.12.0" 329 | } 330 | }, 331 | "nbformat": 4, 332 | "nbformat_minor": 5 333 | } 334 | -------------------------------------------------------------------------------- /cheatsheet.08.Comprehensions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "fcc5aafa", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Comprehensions\n", 9 | "\n", 10 | "List Comprehensions are a special kind of syntax that let us create lists out of other lists, and are incredibly useful when dealing with numbers and with one or two levels of nested for loops.\n", 11 | "\n", 12 | "From the Python 3 [tutorial](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions)\n", 13 | "\n", 14 | "List comprehensions provide a concise way to create lists. [...] or to create a subsequence of those elements that satisfy a certain condition.\n", 15 | "\n", 16 | "Read [Python Comprehensions: A step by step Introduction](https://www.pythoncheatsheet.org/blog/python-comprehensions-step-by-step) for a more in-deep or introduction.\n", 17 | "\n", 18 | "## List comprehension\n", 19 | "\n", 20 | "This is how we create a new list from an existing collection with a For Loop:" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "id": "367d32f0", 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "names = ['Charles', 'Susan', 'Patrick', 'George']\n", 31 | "\n", 32 | "new_list = []\n", 33 | "for n in names:\n", 34 | " new_list.append(n)\n", 35 | "\n", 36 | "new_list\n", 37 | "# ['Charles', 'Susan', 'Patrick', 'George']" 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "id": "7e81411d", 43 | "metadata": {}, 44 | "source": [ 45 | "And this is how we do the same with a List Comprehension:" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "id": "0b0d9a4c", 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "names = ['Charles', 'Susan', 'Patrick', 'George']\n", 56 | "\n", 57 | "new_list = [n for n in names]\n", 58 | "new_list\n", 59 | "# ['Charles', 'Susan', 'Patrick', 'George']" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "id": "831bec11", 65 | "metadata": {}, 66 | "source": [ 67 | "We can do the same with numbers:" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "id": "8e696605", 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "n = [(a, b) for a in range(1, 3) for b in range(1, 3)]\n", 78 | "n\n", 79 | "# [(1, 1), (1, 2), (2, 1), (2, 2)]" 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "id": "82983f3d", 85 | "metadata": {}, 86 | "source": [ 87 | "## Adding conditionals\n", 88 | "\n", 89 | "If we want `new_list` to have only the names that start with C, with a for loop, we would do it like this:" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "id": "126e4a4e", 96 | "metadata": {}, 97 | "outputs": [], 98 | "source": [ 99 | "names = ['Charles', 'Susan', 'Patrick', 'George', 'Carol']\n", 100 | "\n", 101 | "new_list = []\n", 102 | "for n in names:\n", 103 | " if n.startswith('C'):\n", 104 | " new_list.append(n)\n", 105 | "\n", 106 | "print(new_list)\n", 107 | "# ['Charles', 'Carol']" 108 | ] 109 | }, 110 | { 111 | "cell_type": "markdown", 112 | "id": "be072daf", 113 | "metadata": {}, 114 | "source": [ 115 | "In a List Comprehension, we add the `if` statement at the end:" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "id": "c599c9c4", 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [ 125 | "new_list = [n for n in names if n.startswith('C')]\n", 126 | "print(new_list)\n", 127 | "# ['Charles', 'Carol']" 128 | ] 129 | }, 130 | { 131 | "cell_type": "markdown", 132 | "id": "de5cc8b1", 133 | "metadata": {}, 134 | "source": [ 135 | "To use an `if-else` statement in a List Comprehension:" 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": null, 141 | "id": "82f2fa7c", 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [ 145 | "nums = [1, 2, 3, 4, 5, 6]\n", 146 | "new_list = [num*2 if num % 2 == 0 else num for num in nums]\n", 147 | "print(new_list)\n", 148 | "# [1, 4, 3, 8, 5, 12]" 149 | ] 150 | }, 151 | { 152 | "cell_type": "markdown", 153 | "id": "4dcd901d", 154 | "metadata": {}, 155 | "source": [ 156 | "Set and Dict comprehensions\n", 157 | "\n", 158 | "The basics of `list` comprehensions also apply to **sets** and **dictionaries**.\n", 159 | "\n", 160 | "## Set comprehension" 161 | ] 162 | }, 163 | { 164 | "cell_type": "code", 165 | "execution_count": null, 166 | "id": "1c908dc1", 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [ 170 | "b = {\"abc\", \"def\"}\n", 171 | "{s.upper() for s in b}\n", 172 | "{\"ABC\", \"DEF\"}" 173 | ] 174 | }, 175 | { 176 | "cell_type": "markdown", 177 | "id": "91af3362", 178 | "metadata": {}, 179 | "source": [ 180 | "## Dict comprehension" 181 | ] 182 | }, 183 | { 184 | "cell_type": "code", 185 | "execution_count": null, 186 | "id": "d4267d94", 187 | "metadata": {}, 188 | "outputs": [], 189 | "source": [ 190 | "c = {'name': 'Pooka', 'age': 5}\n", 191 | "{v: k for k, v in c.items()}\n", 192 | "{'Pooka': 'name', 5: 'age'}" 193 | ] 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "id": "47247ccb", 198 | "metadata": {}, 199 | "source": [ 200 | "A List comprehension can be generated from a dictionary:" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": null, 206 | "id": "d10ee8af-51d3-4edf-b1ce-b084f4f0d267", 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "c = {'name': 'Pooka', 'age': 5}\n", 211 | "[\"{}:{}\".format(k.upper(), v) for k, v in c.items()]\n", 212 | "['NAME:Pooka', 'AGE:5']" 213 | ] 214 | } 215 | ], 216 | "metadata": { 217 | "kernelspec": { 218 | "display_name": "Python 3 (ipykernel)", 219 | "language": "python", 220 | "name": "python3" 221 | }, 222 | "language_info": { 223 | "codemirror_mode": { 224 | "name": "ipython", 225 | "version": 3 226 | }, 227 | "file_extension": ".py", 228 | "mimetype": "text/x-python", 229 | "name": "python", 230 | "nbconvert_exporter": "python", 231 | "pygments_lexer": "ipython3", 232 | "version": "3.12.0" 233 | } 234 | }, 235 | "nbformat": 4, 236 | "nbformat_minor": 5 237 | } 238 | -------------------------------------------------------------------------------- /cheatsheet.10.String.Formatting.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "d1a8c78d", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python String Formatting\n", 9 | "\n", 10 | "From the [Python 3 documentation](https://docs.python.org/3/library/stdtypes.html?highlight=sprintf#printf-style-string-formatting)\n", 11 | "\n", 12 | "The formatting operations described here (**% operator**) exhibit a variety of quirks that lead to a number of common errors [...]. Using the newer [formatted string literals](https://www.pythoncheatsheet.org/cheatsheet/string-formatting#formatted-string-literals-or-f-strings) [...] helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.\n", 13 | "\n", 14 | "## % operator\n", 15 | "\n", 16 | "Prefer String Literals\n", 17 | "\n", 18 | "For new code, using [str.format](https://www.pythoncheatsheet.org/cheatsheet/string-formatting#strformat), or [formatted string literals](https://www.pythoncheatsheet.org/cheatsheet/string-formatting#formatted-string-literals-or-f-strings) (Python 3.6+) over the `%` operator is strongly recommended." 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "id": "3810a428", 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "name = 'Pete'\n", 29 | "'Hello %s' % name\n", 30 | "# \"Hello Pete\"" 31 | ] 32 | }, 33 | { 34 | "cell_type": "markdown", 35 | "id": "08a1e6a8", 36 | "metadata": {}, 37 | "source": [ 38 | "We can use the `%d` format specifier to convert an int value to a string:" 39 | ] 40 | }, 41 | { 42 | "cell_type": "code", 43 | "execution_count": null, 44 | "id": "c0ca24ac", 45 | "metadata": {}, 46 | "outputs": [], 47 | "source": [ 48 | "num = 5\n", 49 | "'I have %d apples' % num\n", 50 | "# \"I have 5 apples\"" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "id": "8f96d973", 56 | "metadata": {}, 57 | "source": [ 58 | "## str.format\n", 59 | "\n", 60 | "Python 3 introduced a new way to do string formatting that was later back-ported to Python 2.7. This makes the syntax for string formatting more regular." 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": null, 66 | "id": "da42ccdc-3dee-4b20-bcce-4d12db4f944b", 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "name = 'John'\n", 71 | "age = 20" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": null, 77 | "id": "a27e93d9-7da4-4000-a028-b89160d5ba45", 78 | "metadata": {}, 79 | "outputs": [], 80 | "source": [ 81 | "\"Hello I'm {}, my age is {}\".format(name, age)\n", 82 | "# \"Hello I'm John, my age is 20\"" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": null, 88 | "id": "bfb6ad75-a89c-4368-b840-9e7af30349b4", 89 | "metadata": {}, 90 | "outputs": [], 91 | "source": [ 92 | "\"Hello I'm {0}, my age is {1}\".format(name, age)\n", 93 | "# \"Hello I'm John, my age is 20\"" 94 | ] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "id": "7b3d30dd", 99 | "metadata": {}, 100 | "source": [ 101 | "## Formatted String Literals or f-Strings\n", 102 | "\n", 103 | "If your are using Python 3.6+, string `f-Strings` are the recommended way to format strings.\n", 104 | "\n", 105 | "\n", 106 | "\n", 107 | "From the [Python 3 documentation](https://docs.python.org/3/reference/lexical_analysis.html#f-strings)\n", 108 | "\n", 109 | "A formatted string literal or f-string is a string literal that is prefixed with `f` or `F`. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time." 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "id": "51c937ec", 116 | "metadata": {}, 117 | "outputs": [], 118 | "source": [ 119 | "name = 'Elizabeth'\n", 120 | "f'Hello {name}!'\n", 121 | "# 'Hello Elizabeth!'" 122 | ] 123 | }, 124 | { 125 | "cell_type": "markdown", 126 | "id": "5c001a3b", 127 | "metadata": {}, 128 | "source": [ 129 | "It is even possible to do inline arithmetic with it:" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": null, 135 | "id": "2c4062df", 136 | "metadata": {}, 137 | "outputs": [], 138 | "source": [ 139 | "a = 5\n", 140 | "b = 10\n", 141 | "f'Five plus ten is {a + b} and not {2 * (a + b)}.'\n", 142 | "# 'Five plus ten is 15 and not 30.'" 143 | ] 144 | }, 145 | { 146 | "cell_type": "markdown", 147 | "id": "4af7c50c", 148 | "metadata": {}, 149 | "source": [ 150 | "### Multiline f-Strings" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": null, 156 | "id": "710c3597", 157 | "metadata": {}, 158 | "outputs": [], 159 | "source": [ 160 | "name = 'Robert'\n", 161 | "messages = 12\n", 162 | "\n", 163 | "(\n", 164 | " f'Hi, {name}. '\n", 165 | " f'You have {messages} unread messages'\n", 166 | ")\n", 167 | "# 'Hi, Robert. You have 12 unread messages'" 168 | ] 169 | }, 170 | { 171 | "cell_type": "markdown", 172 | "id": "b175de53", 173 | "metadata": {}, 174 | "source": [ 175 | "### The `=` specifier\n", 176 | "\n", 177 | "This will print the expression and its value:" 178 | ] 179 | }, 180 | { 181 | "cell_type": "code", 182 | "execution_count": null, 183 | "id": "80123780", 184 | "metadata": {}, 185 | "outputs": [], 186 | "source": [ 187 | "from datetime import datetime\n", 188 | "now = datetime.now().strftime(\"%b/%d/%Y - %H:%M:%S\")\n", 189 | "f'date and time: {now=}'\n", 190 | "# \"date and time: now='...'\" `...` will be replaced by current time." 191 | ] 192 | }, 193 | { 194 | "cell_type": "markdown", 195 | "id": "a4755731", 196 | "metadata": {}, 197 | "source": [ 198 | "### Adding spaces or characters" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": null, 204 | "id": "81a31449-9026-4a6d-8775-90032020a2a7", 205 | "metadata": {}, 206 | "outputs": [], 207 | "source": [ 208 | "f\"{name.upper() = :-^20}\"\n", 209 | "# 'name.upper() = -------ROBERT-------'" 210 | ] 211 | }, 212 | { 213 | "cell_type": "code", 214 | "execution_count": null, 215 | "id": "e8840697-0b8a-4fcf-908d-12c8735bc9e3", 216 | "metadata": {}, 217 | "outputs": [], 218 | "source": [ 219 | "f\"{name.upper() = :^20}\"\n", 220 | "# 'name.upper() = ROBERT '" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": null, 226 | "id": "6d2e5f6d-88d7-4018-b491-f9f0a3d757de", 227 | "metadata": {}, 228 | "outputs": [], 229 | "source": [ 230 | "f\"{name.upper() = :20}\"\n", 231 | "# 'name.upper() = ROBERT '" 232 | ] 233 | }, 234 | { 235 | "cell_type": "markdown", 236 | "id": "9c7f3c30", 237 | "metadata": {}, 238 | "source": [ 239 | "## Formatting Digits\n", 240 | "\n", 241 | "Adding thousands separator" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": null, 247 | "id": "6d20dc10", 248 | "metadata": {}, 249 | "outputs": [], 250 | "source": [ 251 | "a = 10000000\n", 252 | "f\"{a:,}\"\n", 253 | "# '10,000,000'" 254 | ] 255 | }, 256 | { 257 | "cell_type": "markdown", 258 | "id": "2db6d0f9", 259 | "metadata": {}, 260 | "source": [ 261 | "Rounding" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": null, 267 | "id": "a74af113", 268 | "metadata": {}, 269 | "outputs": [], 270 | "source": [ 271 | "a = 3.1415926\n", 272 | "f\"{a:.2f}\"\n", 273 | "# '3.14'" 274 | ] 275 | }, 276 | { 277 | "cell_type": "markdown", 278 | "id": "f2810cae", 279 | "metadata": {}, 280 | "source": [ 281 | "Showing as Percentage" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": null, 287 | "id": "c9f5f926", 288 | "metadata": {}, 289 | "outputs": [], 290 | "source": [ 291 | "a = 0.816562\n", 292 | "f\"{a:.2%}\"\n", 293 | "# '81.66%'" 294 | ] 295 | }, 296 | { 297 | "cell_type": "markdown", 298 | "id": "f31f7788", 299 | "metadata": {}, 300 | "source": [ 301 | "### Number formatting table\n", 302 | "\n", 303 | "| Number | Format | Output | description |\n", 304 | "| ---------- | ------- | --------- | --------------------------------------------- |\n", 305 | "| 3.1415926 | {:.2f} | 3.14 | Format float 2 decimal places |\n", 306 | "| 3.1415926 | {:+.2f} | +3.14 | Format float 2 decimal places with sign |\n", 307 | "| -1 | {:+.2f} | -1.00 | Format float 2 decimal places with sign |\n", 308 | "| 2.71828 | {:.0f} | 3 | Format float with no decimal places |\n", 309 | "| 4 | {:0>2d} | 04 | Pad number with zeros (left padding, width 2) |\n", 310 | "| 4 | {:x<4d} | 4xxx | Pad number with x’s (right padding, width 4) |\n", 311 | "| 10 | {:x<4d} | 10xx | Pad number with x’s (right padding, width 4) |\n", 312 | "| 1000000 | {:,} | 1,000,000 | Number format with comma separator |\n", 313 | "| 0.35 | {:.2%} | 35.00% | Format percentage |\n", 314 | "| 1000000000 | {:.2e} | 1.00e+09 | Exponent notation |\n", 315 | "| 11 | {:11d} | 11 | Right-aligned (default, width 10) |\n", 316 | "| 11 | {:<11d} | 11 | Left-aligned (width 10) |\n", 317 | "| 11 | {:^11d} | 11 | Center aligned (width 10) |\n", 318 | "\n", 319 | "## Template Strings\n", 320 | "\n", 321 | "A simpler and less powerful mechanism, but it is recommended when handling strings generated by users. Due to their reduced complexity, template strings are a safer choice." 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": null, 327 | "id": "eb00a48d-e582-41ce-8341-58cd3480a3ae", 328 | "metadata": {}, 329 | "outputs": [], 330 | "source": [ 331 | "from string import Template\n", 332 | "name = 'Elizabeth'\n", 333 | "t = Template('Hey $name!')\n", 334 | "t.substitute(name=name)\n", 335 | "# 'Hey Elizabeth!'" 336 | ] 337 | } 338 | ], 339 | "metadata": { 340 | "kernelspec": { 341 | "display_name": "Python 3 (ipykernel)", 342 | "language": "python", 343 | "name": "python3" 344 | }, 345 | "language_info": { 346 | "codemirror_mode": { 347 | "name": "ipython", 348 | "version": 3 349 | }, 350 | "file_extension": ".py", 351 | "mimetype": "text/x-python", 352 | "name": "python", 353 | "nbconvert_exporter": "python", 354 | "pygments_lexer": "ipython3", 355 | "version": "3.12.0" 356 | } 357 | }, 358 | "nbformat": 4, 359 | "nbformat_minor": 5 360 | } 361 | -------------------------------------------------------------------------------- /cheatsheet.14.JSON.and.YAML.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "4c535777", 6 | "metadata": {}, 7 | "source": [ 8 | "# JSON and YAML\n", 9 | "\n", 10 | "## JSON\n", 11 | "\n", 12 | "JSON stands for JavaScript Object Notation and is a lightweight format for storing and transporting data. Json is often used when data is sent from a server to a web page." 13 | ] 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": null, 18 | "id": "4c50f720", 19 | "metadata": {}, 20 | "outputs": [], 21 | "source": [ 22 | "import json\n", 23 | "with open(\"filename.json\", \"r\") as f:\n", 24 | " content = json.load(f)" 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "id": "685855e9", 30 | "metadata": {}, 31 | "source": [ 32 | "Write a JSON file with:" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "id": "9086fc70", 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "import json\n", 43 | "\n", 44 | "content = {\"name\": \"Joe\", \"age\": 20}\n", 45 | "with open(\"filename.json\", \"w\") as f:\n", 46 | " json.dump(content, f, indent=2)" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "id": "6858792c", 52 | "metadata": {}, 53 | "source": [ 54 | "## YAML\n", 55 | "\n", 56 | "Compared to JSON, YAML allows a much better human maintainability and gives ability to add comments. It is a convenient choice for configuration files where a human will have to edit.\n", 57 | "\n", 58 | "There are two main libraries allowing to access to YAML files:\n", 59 | "\n", 60 | "- [PyYaml](https://pypi.python.org/pypi/PyYAML)\n", 61 | "- [Ruamel.yaml](https://pypi.python.org/pypi/ruamel.yaml)\n", 62 | "\n", 63 | "Install them using `pip install` in your virtual environment.\n", 64 | "\n", 65 | "The first one is easier to use but the second one, Ruamel, implements much better the YAML specification, and allow for example to modify a YAML content without altering comments.\n", 66 | "\n", 67 | "Open a YAML file with:" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "id": "db6f318f", 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [ 77 | "from ruamel.yaml import YAML\n", 78 | "\n", 79 | "with open(\"filename.yaml\") as f:\n", 80 | " yaml=YAML()\n", 81 | " yaml.load(f)" 82 | ] 83 | }, 84 | { 85 | "cell_type": "markdown", 86 | "id": "787703d2", 87 | "metadata": {}, 88 | "source": [ 89 | "## Anyconfig\n", 90 | "\n", 91 | "[Anyconfig](https://pypi.python.org/pypi/anyconfig) is a very handy package, allowing to abstract completely the underlying configuration file format. It allows to load a Python dictionary from JSON, YAML, TOML, and so on.\n", 92 | "\n", 93 | "Install it with:" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "id": "2280d98f", 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [ 103 | "%%bash\n", 104 | "pip install anyconfig" 105 | ] 106 | }, 107 | { 108 | "cell_type": "markdown", 109 | "id": "8a89a9c4", 110 | "metadata": {}, 111 | "source": [ 112 | "Usage:" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": null, 118 | "id": "563f4fc0-9081-49f9-b065-98ee6b247001", 119 | "metadata": {}, 120 | "outputs": [], 121 | "source": [ 122 | "import anyconfig\n", 123 | "conf1 = anyconfig.load(\"/path/to/foo/conf.d/a.yml\")" 124 | ] 125 | } 126 | ], 127 | "metadata": { 128 | "kernelspec": { 129 | "display_name": "Python 3 (ipykernel)", 130 | "language": "python", 131 | "name": "python3" 132 | }, 133 | "language_info": { 134 | "codemirror_mode": { 135 | "name": "ipython", 136 | "version": 3 137 | }, 138 | "file_extension": ".py", 139 | "mimetype": "text/x-python", 140 | "name": "python", 141 | "nbconvert_exporter": "python", 142 | "pygments_lexer": "ipython3", 143 | "version": "3.12.0" 144 | } 145 | }, 146 | "nbformat": 4, 147 | "nbformat_minor": 5 148 | } 149 | -------------------------------------------------------------------------------- /cheatsheet.15.Exception.Handling.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "281db0e9", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Exception Handling\n", 9 | "\n", 10 | "[Exception handling](https://en.wikipedia.org/wiki/Exception_handling)\n", 11 | "\n", 12 | "In computing and computer programming, exception handling is the process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing.\n", 13 | "\n", 14 | "Python has many [built-in exceptions](https://docs.python.org/3/library/exceptions.html) that are raised when a program encounters an error, and most external libraries, like the popular [Requests](https://requests.readthedocs.io/en/latest), include his own [custom exceptions](https://requests.readthedocs.io/en/latest/user/quickstart/#errors-and-exceptions) that we will need to deal to.\n", 15 | "\n", 16 | "## Basic exception handling\n", 17 | "\n", 18 | "You can’t divide by zero, that is a mathematical true, and if you try to do it in Python, the interpreter will raise the built-in exception [ZeroDivisionError](https://docs.python.org/3/library/exceptions.html#ZeroDivisionError):" 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "id": "85486829-fd04-4acf-83af-6c06fab7f07f", 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "def divide(dividend , divisor):\n", 29 | " print(dividend / divisor)" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "id": "9d91a18b-9d65-4b65-ac1e-63fb01e47a3a", 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "divide(dividend=10, divisor=5)\n", 40 | "# 5" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "id": "75f51f94-55f2-4d49-ab3a-626248c33005", 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "divide(dividend=10, divisor=0)\n", 51 | "# Traceback (most recent call last):\n", 52 | "# File \"\", line 1, in \n", 53 | "# ZeroDivisionError: division by zero" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "id": "f6515506", 59 | "metadata": {}, 60 | "source": [ 61 | "Let’s say we don’t want our program to stop its execution or show the user an output he will not understand. Say we want to print a useful and clear message, then we need to ***handle\\*** the exception with the `try` and `except` keywords:" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "id": "94c945c4-f7a6-47a8-a825-d87218a5c4f4", 68 | "metadata": {}, 69 | "outputs": [], 70 | "source": [ 71 | "def divide(dividend , divisor):\n", 72 | " try:\n", 73 | " print(dividend / divisor)\n", 74 | " except ZeroDivisionError:\n", 75 | " print('You can not divide by 0')" 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "id": "c73a6702-fcdf-413c-b756-3923f00ff264", 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "divide(dividend=10, divisor=5)\n", 86 | "# 5" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "id": "f6afccdf-8b10-4370-addc-52780d25fb9e", 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "divide(dividend=10, divisor=0)\n", 97 | "# You can not divide by 0" 98 | ] 99 | }, 100 | { 101 | "cell_type": "markdown", 102 | "id": "1bca8b9b", 103 | "metadata": {}, 104 | "source": [ 105 | "## Handling Multiple exceptions using one exception block\n", 106 | "\n", 107 | "You can also handle multiple exceptions in one line like the following without the need to create multiple exception blocks." 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "id": "754b1fda-cf9b-4927-b54d-a0f397f09f59", 114 | "metadata": {}, 115 | "outputs": [], 116 | "source": [ 117 | "def divide(dividend , divisor):\n", 118 | " try:\n", 119 | " var = 'str' + 1\n", 120 | " print(dividend / divisor)\n", 121 | " except (ZeroDivisionError, TypeError) as error:\n", 122 | " print(error)" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "id": "27636006-c55b-4e99-8540-5142bd724d5a", 129 | "metadata": {}, 130 | "outputs": [], 131 | "source": [ 132 | "divide(dividend=10, divisor=5)\n", 133 | "# 5" 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "id": "43524db4-ce88-4af5-9571-4bc3f6fd2e91", 140 | "metadata": {}, 141 | "outputs": [], 142 | "source": [ 143 | "divide(dividend=10, divisor=0)\n", 144 | "# `division by zero` Error message\n", 145 | "# `can only concatenate str (not \"int\") to str` Error message" 146 | ] 147 | }, 148 | { 149 | "cell_type": "markdown", 150 | "id": "edcb4e53", 151 | "metadata": {}, 152 | "source": [ 153 | "## Finally code in exception handling\n", 154 | "\n", 155 | "The code inside the `finally` section is always executed, no matter if an exception has been raised or not:" 156 | ] 157 | }, 158 | { 159 | "cell_type": "code", 160 | "execution_count": null, 161 | "id": "50eb69b1-fce9-4bb2-b6ce-c343358c811b", 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [ 165 | "def divide(dividend , divisor):\n", 166 | " try:\n", 167 | " print(dividend / divisor)\n", 168 | " except ZeroDivisionError:\n", 169 | " print('You can not divide by 0')\n", 170 | " finally:\n", 171 | " print('Execution finished')" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": null, 177 | "id": "3f1dad34-1cb1-420b-9249-49955f59d4b0", 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "divide(dividend=10, divisor=5)\n", 182 | "# 5\n", 183 | "# Execution finished" 184 | ] 185 | }, 186 | { 187 | "cell_type": "code", 188 | "execution_count": null, 189 | "id": "4dcdf1bb-c415-4e18-b7ba-64bc832de89e", 190 | "metadata": {}, 191 | "outputs": [], 192 | "source": [ 193 | "divide(dividend=10, divisor=0)\n", 194 | "# You can not divide by 0\n", 195 | "# Execution finished" 196 | ] 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "id": "7f10a6ac", 201 | "metadata": {}, 202 | "source": [ 203 | "## Custom Exceptions\n", 204 | "\n", 205 | "Custom exceptions initialize by creating a `class` that inherits from the base `Exception` class of Python, and are raised using the `raise` keyword:" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "id": "80ba8617", 212 | "metadata": {}, 213 | "outputs": [], 214 | "source": [ 215 | "class MyCustomException(Exception):\n", 216 | " pass\n", 217 | "\n", 218 | " raise MyCustomException\n", 219 | "# Traceback (most recent call last):\n", 220 | "# File \"\", line 1, in \n", 221 | "# __main__.MyCustomException" 222 | ] 223 | }, 224 | { 225 | "cell_type": "markdown", 226 | "id": "dfcb4bc9", 227 | "metadata": {}, 228 | "source": [ 229 | "To declare a custom exception message, you can pass it as a parameter:" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": null, 235 | "id": "10e27f0c", 236 | "metadata": {}, 237 | "outputs": [], 238 | "source": [ 239 | "class MyCustomException(Exception):\n", 240 | " pass\n", 241 | " \n", 242 | " raise MyCustomException('A custom message for my custom exception')\n", 243 | "# Traceback (most recent call last):\n", 244 | "# File \"\", line 1, in \n", 245 | "# __main__.MyCustomException: A custom message for my custom exception" 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "id": "92288d8e", 251 | "metadata": {}, 252 | "source": [ 253 | "Handling a custom exception is the same as any other:" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": null, 259 | "id": "920e7df8-6ee3-4dca-ac61-a7b85ff29044", 260 | "metadata": {}, 261 | "outputs": [], 262 | "source": [ 263 | "try:\n", 264 | "raise MyCustomException('A custom message for my custom exception')\n", 265 | "except MyCustomException:\n", 266 | " print('My custom exception was raised')\n", 267 | "\n", 268 | "# My custom exception was raised" 269 | ] 270 | } 271 | ], 272 | "metadata": { 273 | "kernelspec": { 274 | "display_name": "Python 3 (ipykernel)", 275 | "language": "python", 276 | "name": "python3" 277 | }, 278 | "language_info": { 279 | "codemirror_mode": { 280 | "name": "ipython", 281 | "version": 3 282 | }, 283 | "file_extension": ".py", 284 | "mimetype": "text/x-python", 285 | "name": "python", 286 | "nbconvert_exporter": "python", 287 | "pygments_lexer": "ipython3", 288 | "version": "3.12.0" 289 | } 290 | }, 291 | "nbformat": 4, 292 | "nbformat_minor": 5 293 | } 294 | -------------------------------------------------------------------------------- /cheatsheet.16.Debugging.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "8dc88c4e", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Debugging\n", 9 | "\n", 10 | "[Finding and resolving bugs](https://en.wikipedia.org/wiki/Debugging)\n", 11 | "\n", 12 | "In computer programming and software development, debugging is the process of finding and resolving bugs (defects or problems that prevent correct operation) within computer programs, software, or systems.\n", 13 | "\n", 14 | "## Raising Exceptions\n", 15 | "\n", 16 | "Exceptions are raised with a raise statement. In code, a raise statement consists of the following:\n", 17 | "\n", 18 | "- The `raise` keyword\n", 19 | "- A call to the `Exception()` function\n", 20 | "- A string with a helpful error message passed to the `Exception()` function" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "id": "aa427ffd", 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "raise Exception('This is the error message.')\n", 31 | "# Traceback (most recent call last):\n", 32 | "# File \"\", line 1, in \n", 33 | "# raise Exception('This is the error message.')\n", 34 | "# Exception: This is the error message." 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "id": "7fe5df41", 40 | "metadata": {}, 41 | "source": [ 42 | "Typically, it’s the code that calls the function, not the function itself, that knows how to handle an exception. So, you will commonly see a raise statement inside a function and the `try` and `except` statements in the code calling the function." 43 | ] 44 | }, 45 | { 46 | "cell_type": "code", 47 | "execution_count": null, 48 | "id": "38153713", 49 | "metadata": {}, 50 | "outputs": [], 51 | "source": [ 52 | "def box_print(symbol, width, height):\n", 53 | " if len(symbol) != 1:\n", 54 | " raise Exception('Symbol must be a single character string.')\n", 55 | " if width <= 2:\n", 56 | " raise Exception('Width must be greater than 2.')\n", 57 | " if height <= 2:\n", 58 | " raise Exception('Height must be greater than 2.')\n", 59 | " print(symbol * width)\n", 60 | " for i in range(height - 2):\n", 61 | " print(symbol + (' ' * (width - 2)) + symbol)\n", 62 | " print(symbol * width)\n", 63 | "\n", 64 | "for sym, w, h in (('*', 4, 4), ('O', 20, 5), ('x', 1, 3), ('ZZ', 3, 3)):\n", 65 | " try:\n", 66 | " box_print(sym, w, h)\n", 67 | " except Exception as err:\n", 68 | " print('An exception happened: ' + str(err))\n", 69 | "\n", 70 | "# ****\n", 71 | "# * *\n", 72 | "# * *\n", 73 | "# ****\n", 74 | "# OOOOOOOOOOOOOOOOOOOO\n", 75 | "# O O\n", 76 | "# O O\n", 77 | "# O O\n", 78 | "# OOOOOOOOOOOOOOOOOOOO\n", 79 | "# An exception happened: Width must be greater than 2.\n", 80 | "# An exception happened: Symbol must be a single character string." 81 | ] 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "id": "c4f20f41", 86 | "metadata": {}, 87 | "source": [ 88 | "Read more about [Exception Handling](https://www.pythoncheatsheet.org/cheatsheet/exception-handling).\n", 89 | "\n", 90 | "## Getting the Traceback as a string\n", 91 | "\n", 92 | "The `traceback` is displayed by Python whenever a raised exception goes unhandled. But can also obtain it as a string by calling traceback.format_exc(). This function is useful if you want the information from an exception’s traceback but also want an except statement to gracefully handle the exception. You will need to import Python’s traceback module before calling this function." 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "id": "f47a013b", 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "import traceback\n", 103 | "\n", 104 | "try:\n", 105 | " raise Exception('This is the error message.')\n", 106 | "except:\n", 107 | " with open('errorInfo.txt', 'w') as error_file:\n", 108 | " error_file.write(traceback.format_exc())\n", 109 | " print('The traceback info was written to errorInfo.txt.')\n", 110 | "\n", 111 | "# 116\n", 112 | "# The traceback info was written to errorInfo.txt." 113 | ] 114 | }, 115 | { 116 | "cell_type": "markdown", 117 | "id": "3b344f5a", 118 | "metadata": {}, 119 | "source": [ 120 | "The 116 is the return value from the `write()` method, since 116 characters were written to the file. The `traceback` text was written to errorInfo.txt." 121 | ] 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "id": "3fda7536-5ef5-4723-976a-7075bd04395e", 126 | "metadata": {}, 127 | "source": [ 128 | "```\n", 129 | "Traceback (most recent call last):\n", 130 | " File \"\", line 2, in \n", 131 | "Exception: This is the error message.\n", 132 | "```" 133 | ] 134 | }, 135 | { 136 | "cell_type": "markdown", 137 | "id": "1cffeaa5", 138 | "metadata": {}, 139 | "source": [ 140 | "## Assertions\n", 141 | "\n", 142 | "An assertion is a sanity check to make sure your code isn’t doing something obviously wrong. These sanity checks are performed by `assert` statements. If the sanity check fails, then an `AssertionError` exception is raised. In code, an `assert` statement consists of the following:\n", 143 | "\n", 144 | "- The `assert` keyword\n", 145 | "- A condition (that is, an expression that evaluates to `True` or `False`)\n", 146 | "- A comma\n", 147 | "- A `string` to display when the condition is `False`" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": null, 153 | "id": "80e24a81", 154 | "metadata": {}, 155 | "outputs": [], 156 | "source": [ 157 | "pod_bay_door_status = 'open'\n", 158 | "assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\n", 159 | "\n", 160 | "pod_bay_door_status = 'I\\'m sorry, Dave. I\\'m afraid I can\\'t do that.'\n", 161 | "assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\n", 162 | "# Traceback (most recent call last):\n", 163 | "# File \"\", line 1, in \n", 164 | "# assert pod_bay_door_status == 'open', 'The pod bay doors need to be \"open\".'\n", 165 | "# AssertionError: The pod bay doors need to be \"open\"." 166 | ] 167 | }, 168 | { 169 | "cell_type": "markdown", 170 | "id": "82f57f10", 171 | "metadata": {}, 172 | "source": [ 173 | "In plain English, an assert statement says, “I assert that this condition holds true, and if not, there is a bug somewhere in the program.” Unlike exceptions, your code should not handle assert statements with try and except; if an assert fails, your program should crash. By failing fast like this, you shorten the time between the original cause of the bug and when you first notice the bug. This will reduce the amount of code you will have to check before finding the code that’s causing the bug.\n", 174 | "\n", 175 | "### Disabling Assertions\n", 176 | "\n", 177 | "Assertions can be disabled by passing the `-O` option when running Python.\n", 178 | "\n", 179 | "## Logging\n", 180 | "\n", 181 | "To enable the `logging` module to display log messages on your screen as your program runs, copy the following to the top of your program:" 182 | ] 183 | }, 184 | { 185 | "cell_type": "code", 186 | "execution_count": null, 187 | "id": "b3bb1b68", 188 | "metadata": {}, 189 | "outputs": [], 190 | "source": [ 191 | "import logging\n", 192 | "logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')" 193 | ] 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "id": "04be67bc", 198 | "metadata": {}, 199 | "source": [ 200 | "Say you wrote a function to calculate the factorial of a number. In mathematics, factorial 4 is 1 × 2 × 3 × 4, or 24. Factorial 7 is 1 × 2 × 3 × 4 × 5 × 6 × 7, or 5,040. Open a new file editor window and enter the following code. It has a bug in it, but you will also enter several log messages to help yourself figure out what is going wrong. Save the program as factorialLog.py." 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": null, 206 | "id": "dfcce2fc", 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "import logging\n", 211 | "logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(levelname)s- %(message)s')\n", 212 | "logging.debug('Start of program')\n", 213 | "\n", 214 | "def factorial(n):\n", 215 | " logging.debug('Start of factorial(%s)' % (n))\n", 216 | " total = 1\n", 217 | " for i in range(1, n + 1):\n", 218 | " total *= i\n", 219 | " logging.debug('i is ' + str(i) + ', total is ' + str(total))\n", 220 | " logging.debug('End of factorial(%s)' % (n))\n", 221 | " return total\n", 222 | "\n", 223 | "print(factorial(5))\n", 224 | "logging.debug('End of program')\n", 225 | "# 2015-05-23 16:20:12,664 - DEBUG - Start of program\n", 226 | "# 2015-05-23 16:20:12,664 - DEBUG - Start of factorial(5)\n", 227 | "# 2015-05-23 16:20:12,665 - DEBUG - i is 0, total is 0\n", 228 | "# 2015-05-23 16:20:12,668 - DEBUG - i is 1, total is 0\n", 229 | "# 2015-05-23 16:20:12,670 - DEBUG - i is 2, total is 0\n", 230 | "# 2015-05-23 16:20:12,673 - DEBUG - i is 3, total is 0\n", 231 | "# 2015-05-23 16:20:12,675 - DEBUG - i is 4, total is 0\n", 232 | "# 2015-05-23 16:20:12,678 - DEBUG - i is 5, total is 0\n", 233 | "# 2015-05-23 16:20:12,680 - DEBUG - End of factorial(5)\n", 234 | "# 0\n", 235 | "# 2015-05-23 16:20:12,684 - DEBUG - End of program" 236 | ] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "id": "00ab4727", 241 | "metadata": {}, 242 | "source": [ 243 | "## Logging Levels\n", 244 | "\n", 245 | "Logging levels provide a way to categorize your log messages by importance. There are five logging levels, described in Table 10-1 from least to most important. Messages can be logged at each level using a different logging function.\n", 246 | "\n", 247 | "| Level | Logging Function | Description |\n", 248 | "| ---------- | -------------------- | ------------------------------------------------------------ |\n", 249 | "| `DEBUG` | `logging.debug()` | The lowest level. Used for small details. Usually you care about these messages only when diagnosing problems. |\n", 250 | "| `INFO` | `logging.info()` | Used to record information on general events in your program or confirm that things are working at their point in the program. |\n", 251 | "| `WARNING` | `logging.warning()` | Used to indicate a potential problem that doesn’t prevent the program from working but might do so in the future. |\n", 252 | "| `ERROR` | `logging.error()` | Used to record an error that caused the program to fail to do something. |\n", 253 | "| `CRITICAL` | `logging.critical()` | The highest level. Used to indicate a fatal error that has caused or is about to cause the program to stop running entirely. |\n", 254 | "\n", 255 | "## Disabling Logging\n", 256 | "\n", 257 | "After you’ve debugged your program, you probably don’t want all these log messages cluttering the screen. The logging.disable() function disables these so that you don’t have to go into your program and remove all the logging calls by hand." 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": null, 263 | "id": "fabce83c", 264 | "metadata": {}, 265 | "outputs": [], 266 | "source": [ 267 | "import logging\n", 268 | "\n", 269 | "logging.basicConfig(level=logging.INFO, format=' %(asctime)s -%(levelname)s - %(message)s')\n", 270 | "logging.critical('Critical error! Critical error!')\n", 271 | "# 2015-05-22 11:10:48,054 - CRITICAL - Critical error! Critical error!\n", 272 | "\n", 273 | "logging.disable(logging.CRITICAL)\n", 274 | "logging.critical('Critical error! Critical error!')\n", 275 | "logging.error('Error! Error!')" 276 | ] 277 | }, 278 | { 279 | "cell_type": "markdown", 280 | "id": "e396bc9d", 281 | "metadata": {}, 282 | "source": [ 283 | "## Logging to a File\n", 284 | "\n", 285 | "Instead of displaying the log messages to the screen, you can write them to a text file. The `logging.basicConfig()` function takes a filename keyword argument, like so:" 286 | ] 287 | }, 288 | { 289 | "cell_type": "code", 290 | "execution_count": null, 291 | "id": "d7d68efe-b206-4c94-9af2-f5875eb522cb", 292 | "metadata": {}, 293 | "outputs": [], 294 | "source": [ 295 | "import logging\n", 296 | "logging.basicConfig(filename='myProgramLog.txt', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')" 297 | ] 298 | } 299 | ], 300 | "metadata": { 301 | "kernelspec": { 302 | "display_name": "Python 3 (ipykernel)", 303 | "language": "python", 304 | "name": "python3" 305 | }, 306 | "language_info": { 307 | "codemirror_mode": { 308 | "name": "ipython", 309 | "version": 3 310 | }, 311 | "file_extension": ".py", 312 | "mimetype": "text/x-python", 313 | "name": "python", 314 | "nbconvert_exporter": "python", 315 | "pygments_lexer": "ipython3", 316 | "version": "3.12.0" 317 | } 318 | }, 319 | "nbformat": 4, 320 | "nbformat_minor": 5 321 | } 322 | -------------------------------------------------------------------------------- /cheatsheet.17.Args.and.Kwargs.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "01a22a9b", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Args and Kwargs\n", 9 | "\n", 10 | "[Python args and kwargs Made Easy](https://docs.python.org/3/tutorial/index.html)\n", 11 | "\n", 12 | "`*args` and `**kwargs` may seem scary, but the truth is that they are not that difficult to grasp and have the power to grant your functions with lots of flexibility.\n", 13 | "\n", 14 | "Read the article [Python *args and **kwargs Made Easy](https://www.pythoncheatsheet.org/blog/python-easy-args-kwargs) for a more in deep introduction.\n", 15 | "\n", 16 | "## Args and Kwargs\n", 17 | "\n", 18 | "`*args` and `**kwargs` allow you to pass an undefined number of arguments and keywords when calling a function." 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "id": "a806d273-39b7-4bd6-aa99-3978808d0670", 25 | "metadata": {}, 26 | "outputs": [], 27 | "source": [ 28 | "def some_function(*args, **kwargs):\n", 29 | " pass" 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "id": "526afd8f-8af5-4197-9895-ebfbfe611565", 36 | "metadata": {}, 37 | "outputs": [], 38 | "source": [ 39 | "# call some_function with any number of arguments\n", 40 | "some_function(arg1, arg2, arg3)" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": null, 46 | "id": "f4ed789f-eb77-4341-9122-fb33c18f258c", 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "# call some_function with any number of keywords\n", 51 | "some_function(key1=arg1, key2=arg2, key3=arg3)" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "id": "7e4753d4-a62d-45d6-88cb-6d4a17c75154", 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "# call both, arguments and keywords\n", 62 | "some_function(arg, key1=arg1)" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": null, 68 | "id": "7d1ad99b-6270-465f-98db-f4746f67ceae", 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "# or none\n", 73 | "some_function()" 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "id": "522c6c67", 79 | "metadata": {}, 80 | "source": [ 81 | "Python conventions\n", 82 | "\n", 83 | "The words `*args` and `**kwargs` are conventions. They are not imposed by the interpreter, but considered good practice by the Python community.\n", 84 | "\n", 85 | "## args\n", 86 | "\n", 87 | "You can access the *arguments* through the `args` variable:" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": null, 93 | "id": "5be68331-4755-4a8b-80f4-7ec7e8a2e934", 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "def some_function(*args):\n", 98 | "print(f'Arguments passed: {args} as {type(args)}')" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "id": "1d3481eb-1f16-4a81-b301-fca677376eec", 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "some_function('arg1', 'arg2', 'arg3')\n", 109 | "# Arguments passed: ('arg1', 'arg2', 'arg3') as " 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "id": "ed8f0dff", 115 | "metadata": {}, 116 | "source": [ 117 | "## kwargs\n", 118 | "\n", 119 | "Keywords are accessed through the `kwargs` variable:\n" 120 | ] 121 | }, 122 | { 123 | "cell_type": "code", 124 | "execution_count": null, 125 | "id": "defcd79f-f46b-40da-955c-6194082132bf", 126 | "metadata": {}, 127 | "outputs": [], 128 | "source": [ 129 | "def some_function(**kwargs):\n", 130 | " print(f'keywords: {kwargs} as {type(kwargs)}')\n", 131 | "\n", 132 | "some_function(key1='arg1', key2='arg2')\n", 133 | "# keywords: {'key1': 'arg1', 'key2': 'arg2'} as " 134 | ] 135 | } 136 | ], 137 | "metadata": { 138 | "kernelspec": { 139 | "display_name": "Python 3 (ipykernel)", 140 | "language": "python", 141 | "name": "python3" 142 | }, 143 | "language_info": { 144 | "codemirror_mode": { 145 | "name": "ipython", 146 | "version": 3 147 | }, 148 | "file_extension": ".py", 149 | "mimetype": "text/x-python", 150 | "name": "python", 151 | "nbconvert_exporter": "python", 152 | "pygments_lexer": "ipython3", 153 | "version": "3.12.0" 154 | } 155 | }, 156 | "nbformat": 4, 157 | "nbformat_minor": 5 158 | } 159 | -------------------------------------------------------------------------------- /cheatsheet.18.Context.Manager.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "69101d36", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Context Manager\n", 9 | "\n", 10 | "While Python’s context managers are widely used, few understand the purpose behind their use. These statements, commonly used with reading and writing files, assist the application in conserving system memory and improve resource management by ensuring specific resources are only in use for certain processes.\n", 11 | "\n", 12 | "## The with statement\n", 13 | "\n", 14 | "A context manager is an object that is notified when a context (a block of code) starts and ends. You commonly use one with the `with` statement. It takes care of the notifying.\n", 15 | "\n", 16 | "For example, file objects are context managers. When a context ends, the file object is closed automatically:" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "id": "2ce7299b", 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "with open(filename) as f:\n", 27 | " file_contents = f.read()\n", 28 | "\n", 29 | "# the open_file object has automatically been closed." 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "id": "512881df", 35 | "metadata": {}, 36 | "source": [ 37 | "Anything that ends execution of the block causes the context manager’s exit method to be called. This includes exceptions, and can be useful when an error causes you to prematurely exit an open file or connection. Exiting a script without properly closing files/connections is a bad idea, that may cause data loss or other problems. By using a context manager, you can ensure that precautions are always taken to prevent damage or loss in this way.\n", 38 | "\n", 39 | "## Writing your own context manager\n", 40 | "\n", 41 | "It is also possible to write a context manager using generator syntax thanks to the `contextlib.contextmanager` decorator:" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "id": "5cf74a01", 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "import contextlib\n", 52 | "@contextlib.contextmanager\n", 53 | "def context_manager(num):\n", 54 | " print('Enter')\n", 55 | " yield num + 1\n", 56 | " print('Exit')\n", 57 | "\n", 58 | "with context_manager(2) as cm:\n", 59 | "# the following instructions are run when\n", 60 | "# the 'yield' point of the context manager is\n", 61 | "# reached. 'cm' will have the value that was yielded\n", 62 | " print('Right in the middle with cm = {}'.format(cm))\n", 63 | "\n", 64 | "# Enter\n", 65 | "# Right in the middle with cm = 3\n", 66 | "# Exit" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "id": "0d61cbc6", 72 | "metadata": {}, 73 | "source": [ 74 | "## Class based context manager\n", 75 | "\n", 76 | "You can define class based context manager. The key methods are `__enter__` and `__exit__`" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "id": "259a43a9", 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "class ContextManager:\n", 87 | " def __enter__(self, *args, **kwargs):\n", 88 | " print(\"--enter--\")\n", 89 | "\n", 90 | "def __exit__(self, *args):\n", 91 | " print(\"--exit--\")\n", 92 | "\n", 93 | "with ContextManager():\n", 94 | " print(\"test\")\n", 95 | "#--enter--\n", 96 | "#test\n", 97 | "#--exit--" 98 | ] 99 | } 100 | ], 101 | "metadata": { 102 | "kernelspec": { 103 | "display_name": "Python 3 (ipykernel)", 104 | "language": "python", 105 | "name": "python3" 106 | }, 107 | "language_info": { 108 | "codemirror_mode": { 109 | "name": "ipython", 110 | "version": 3 111 | }, 112 | "file_extension": ".py", 113 | "mimetype": "text/x-python", 114 | "name": "python", 115 | "nbconvert_exporter": "python", 116 | "pygments_lexer": "ipython3", 117 | "version": "3.12.0" 118 | } 119 | }, 120 | "nbformat": 4, 121 | "nbformat_minor": 5 122 | } 123 | -------------------------------------------------------------------------------- /cheatsheet.19.OOP.Basics.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "16572b35", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python OOP Basics\n", 9 | "\n", 10 | "[Object-Oriented Programming](https://en.wikipedia.org/wiki/Object-oriented_programming)\n", 11 | "\n", 12 | "Object-oriented programming (OOP) is a programming paradigm based on the concept of \"objects\", which can contain data and code. The data is in the form of fields (often known as attributes or properties), and the code is in the form of procedures (often known as methods).\n", 13 | "\n", 14 | "## Encapsulation\n", 15 | "\n", 16 | "Encapsulation is one of the fundamental concepts of object-oriented programming, which helps to protect the data and methods of an object from unauthorized access and modification. It is a way to achieve data abstraction, which means that the implementation details of an object are hidden from the outside world, and only the essential information is exposed.\n", 17 | "\n", 18 | "In Python, encapsulation can be achieved by using access modifiers. Access modifiers are keywords that define the accessibility of attributes and methods in a class. The three access modifiers available in Python are public, private, and protected. However, Python does not have an explicit way of defining access modifiers like some other programming languages such as Java and C++. Instead, it uses a convention of using underscore prefixes to indicate the access level.\n", 19 | "\n", 20 | "In the given code example, the class MyClass has two attributes, _protected_var and __private_var. The _protected_var is marked as protected by using a single underscore prefix. This means that the attribute can be accessed within the class and its subclasses but not outside the class. The __private_var is marked as private by using two underscore prefixes. This means that the attribute can only be accessed within the class and not outside the class, not even in its subclasses.\n", 21 | "\n", 22 | "When we create an object of the MyClass class, we can access the _protected_var attribute using the object name with a single underscore prefix. However, we cannot access the __private_var attribute using the object name, as it is hidden from the outside world. If we try to access the __private_var attribute, we will get an AttributeError as shown in the code.\n", 23 | "\n", 24 | "In summary, encapsulation is an important concept in object-oriented programming that helps to protect the implementation details of an object. In Python, we can achieve encapsulation by using access modifiers and using underscore prefixes to indicate the access level." 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": null, 30 | "id": "812e5d82", 31 | "metadata": {}, 32 | "outputs": [], 33 | "source": [ 34 | "# Define a class named MyClass\n", 35 | "class MyClass:\n", 36 | "\n", 37 | " # Constructor method that initializes the class object\n", 38 | " def __init__(self):\n", 39 | "\n", 40 | " # Define a protected variable with an initial value of 10\n", 41 | " # The variable name starts with a single underscore, which indicates protected access\n", 42 | " self._protected_var = 10\n", 43 | "\n", 44 | " # Define a private variable with an initial value of 20\n", 45 | " # The variable name starts with two underscores, which indicates private access\n", 46 | " self.__private_var = 20\n", 47 | "\n", 48 | "# Create an object of MyClass class\n", 49 | "obj = MyClass()\n", 50 | "\n", 51 | "# Access the protected variable using the object name and print its value\n", 52 | "# The protected variable can be accessed outside the class but\n", 53 | "# it is intended to be used within the class or its subclasses\n", 54 | "print(obj._protected_var) # output: 10\n", 55 | "\n", 56 | "# Try to access the private variable using the object name and print its value\n", 57 | "# The private variable cannot be accessed outside the class, even by its subclasses\n", 58 | "# This will raise an AttributeError because the variable is not accessible outside the class\n", 59 | "print(obj.__private_var) # AttributeError: 'MyClass' object has no attribute '__private_var'" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "id": "18819e54", 65 | "metadata": {}, 66 | "source": [ 67 | "## Inheritance\n", 68 | "\n", 69 | "Inheritance promotes code reuse and allows you to create a hierarchy of classes that share common attributes and methods. It helps in creating clean and organized code by keeping related functionality in one place and promoting the concept of modularity. The base class from which a new class is derived is also known as a parent class, and the new class is known as the child class or subclass.\n", 70 | "\n", 71 | "In the code, we define a class named Animal which has a constructor method that initializes the class object with a name attribute and a method named speak. The speak method is defined in the Animal class but does not have a body.\n", 72 | "\n", 73 | "We then define two subclasses named Dog and Cat which inherit from the Animal class. These subclasses override the speak method of the Animal class.\n", 74 | "\n", 75 | "We create a Dog object with a name attribute “Rover” and a Cat object with a name attribute “Whiskers”. We call the speak method of the Dog object using dog.speak(), and it prints “Woof!” because the speak method of the Dog class overrides the speak method of the Animal class. Similarly, we call the speak method of the Cat object using cat.speak(), and it prints “Meow!” because the speak method of the Cat class overrides the speak method of the Animal class." 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "id": "4d0b504e", 82 | "metadata": {}, 83 | "outputs": [], 84 | "source": [ 85 | "# Define a class named Animal\n", 86 | "class Animal:\n", 87 | "\n", 88 | " # Constructor method that initializes the class object with a name attribute\n", 89 | " def __init__(self, name):\n", 90 | " self.name = name\n", 91 | "\n", 92 | " # Method that is defined in the Animal class but does not have a body\n", 93 | " # This method will be overridden in the subclasses of Animal\n", 94 | " def speak(self):\n", 95 | " print(\"\")\n", 96 | "\n", 97 | "# Define a subclass named Dog that inherits from the Animal class\n", 98 | "class Dog(Animal):\n", 99 | "\n", 100 | " # Override the speak method of the Animal class\n", 101 | " def speak(self):\n", 102 | " print(\"Woof!\")\n", 103 | "\n", 104 | "# Define a subclass named Cat that inherits from the Animal class\n", 105 | "class Cat(Animal):\n", 106 | "\n", 107 | " # Override the speak method of the Animal class\n", 108 | " def speak(self):\n", 109 | " print(\"Meow!\")\n", 110 | "\n", 111 | "# Create a Dog object with a name attribute \"Rover\"\n", 112 | "dog = Dog(\"Rover\")\n", 113 | "\n", 114 | "# Create a Cat object with a name attribute \"Whiskers\"\n", 115 | "cat = Cat(\"Whiskers\")\n", 116 | "\n", 117 | "# Call the speak method of the Dog class and print the output\n", 118 | "# The speak method of the Dog class overrides the speak method of the Animal class\n", 119 | "# Therefore, when we call the speak method of the Dog object, it will print \"Woof!\"\n", 120 | "dog.speak() # output: Woof!\n", 121 | "\n", 122 | "# Call the speak method of the Cat class and print the output\n", 123 | "# The speak method of the Cat class overrides the speak method of the Animal class\n", 124 | "# Therefore, when we call the speak method of the Cat object, it will print \"Meow!\"\n", 125 | "cat.speak() # output: Meow!" 126 | ] 127 | }, 128 | { 129 | "cell_type": "markdown", 130 | "id": "ef896f40", 131 | "metadata": {}, 132 | "source": [ 133 | "## Polymorphism\n", 134 | "\n", 135 | "Polymorphism is an important concept in object-oriented programming that allows you to write code that can work with objects of different classes in a uniform way. In Python, polymorphism is achieved by using method overriding or method overloading.\n", 136 | "\n", 137 | "Method overriding is when a subclass provides its own implementation of a method that is already defined in its parent class. This allows the subclass to modify the behavior of the method without changing its name or signature.\n", 138 | "\n", 139 | "Method overloading is when multiple methods have the same name but different parameters. Python does not support method overloading directly, but it can be achieved using default arguments or variable-length arguments.\n", 140 | "\n", 141 | "Polymorphism makes it easier to write flexible and reusable code. It allows you to write code that can work with different objects without needing to know their specific types." 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": null, 147 | "id": "4aba6552", 148 | "metadata": {}, 149 | "outputs": [], 150 | "source": [ 151 | "#The Shape class is defined with an abstract area method, which is intended to be overridden by subclasses.\n", 152 | "class Shape:\n", 153 | " def area(self):\n", 154 | " pass\n", 155 | "\n", 156 | "class Rectangle(Shape):\n", 157 | " # The Rectangle class is defined with an __init__ method that initializes\n", 158 | " # width and height instance variables.\n", 159 | " # It also defines an area method that calculates and returns\n", 160 | " # the area of a rectangle using the width and height instance variables.\n", 161 | " def __init__(self, width, height):\n", 162 | " self.width = width # Initialize width instance variable\n", 163 | " self.height = height # Initialize height instance variable\n", 164 | "\n", 165 | " def area(self):\n", 166 | " return self.width * self.height # Return area of rectangle\n", 167 | "\n", 168 | "\n", 169 | " # The Circle class is defined with an __init__ method\n", 170 | " # that initializes a radius instance variable.\n", 171 | " # It also defines an area method that calculates and\n", 172 | " # returns the area of a circle using the radius instance variable.\n", 173 | "class Circle(Shape):\n", 174 | " def __init__(self, radius):\n", 175 | " self.radius = radius # Initialize radius instance variable\n", 176 | "\n", 177 | " def area(self):\n", 178 | " return 3.14 * self.radius ** 2 # Return area of circle using pi * r^2\n", 179 | "\n", 180 | "# The shapes list is created with one Rectangle object and one Circle object. The for\n", 181 | "# loop iterates over each object in the list and calls the area method of each object\n", 182 | "# The output will be the area of the rectangle (20) and the area of the circle (153.86).\n", 183 | "shapes = [Rectangle(4, 5), Circle(7)] # Create a list of Shape objects\n", 184 | "for shape in shapes:\n", 185 | " print(shape.area()) # Output the area of each Shape object" 186 | ] 187 | }, 188 | { 189 | "cell_type": "markdown", 190 | "id": "392f655f", 191 | "metadata": {}, 192 | "source": [ 193 | "## Abstraction\n", 194 | "\n", 195 | "Abstraction is an important concept in object-oriented programming (OOP) because it allows you to focus on the essential features of an object or system while ignoring the details that aren’t relevant to the current context. By reducing complexity and hiding unnecessary details, abstraction can make code more modular, easier to read, and easier to maintain.\n", 196 | "\n", 197 | "In Python, abstraction can be achieved by using abstract classes or interfaces. An abstract class is a class that cannot be instantiated directly, but is meant to be subclassed by other classes. It often includes abstract methods that have no implementation, but provide a template for how the subclass should be implemented. This allows the programmer to define a common interface for a group of related classes, while still allowing each class to have its own specific behavior.\n", 198 | "\n", 199 | "An interface, on the other hand, is a collection of method signatures that a class must implement in order to be considered “compatible” with the interface. Interfaces are often used to define a common set of methods that multiple classes can implement, allowing them to be used interchangeably in certain contexts.\n", 200 | "\n", 201 | "Python does not have built-in support for abstract classes or interfaces, but they can be implemented using the abc (abstract base class) module. This module provides the ABC class and the abstractmethod decorator, which can be used to define abstract classes and methods.\n", 202 | "\n", 203 | "Overall, abstraction is a powerful tool for managing complexity and improving code quality in object-oriented programming, and Python provides a range of options for achieving abstraction in your code." 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": null, 209 | "id": "6edb539e", 210 | "metadata": {}, 211 | "outputs": [], 212 | "source": [ 213 | "# Import the abc module to define abstract classes and methods\n", 214 | "from abc import ABC, abstractmethod\n", 215 | "\n", 216 | "# Define an abstract class called Shape that has an abstract method called area\n", 217 | "class Shape(ABC):\n", 218 | " @abstractmethod\n", 219 | " def area(self):\n", 220 | " pass\n", 221 | "\n", 222 | "# Define a Rectangle class that inherits from Shape\n", 223 | "class Rectangle(Shape):\n", 224 | " def __init__(self, width, height):\n", 225 | " self.width = width\n", 226 | " self.height = height\n", 227 | "\n", 228 | " # Implement the area method for Rectangles\n", 229 | " def area(self):\n", 230 | " return self.width * self.height\n", 231 | "\n", 232 | "# Define a Circle class that also inherits from Shape\n", 233 | "class Circle(Shape):\n", 234 | " def __init__(self, radius):\n", 235 | " self.radius = radius\n", 236 | "\n", 237 | " # Implement the area method for Circles\n", 238 | " def area(self):\n", 239 | " return 3.14 * self.radius ** 2\n", 240 | "\n", 241 | "# Create a list of shapes that includes both Rectangles and Circles\n", 242 | "shapes = [Rectangle(4, 5), Circle(7)]\n", 243 | "\n", 244 | "# Loop through each shape in the list and print its area\n", 245 | "for shape in shapes:\n", 246 | " print(shape.area())" 247 | ] 248 | }, 249 | { 250 | "cell_type": "markdown", 251 | "id": "a0b8cc18", 252 | "metadata": {}, 253 | "source": [ 254 | "These are some of the basic OOP principles in Python. This page is currently in progress and more detailed examples and explanations will be coming soon." 255 | ] 256 | } 257 | ], 258 | "metadata": { 259 | "kernelspec": { 260 | "display_name": "Python 3 (ipykernel)", 261 | "language": "python", 262 | "name": "python3" 263 | }, 264 | "language_info": { 265 | "codemirror_mode": { 266 | "name": "ipython", 267 | "version": 3 268 | }, 269 | "file_extension": ".py", 270 | "mimetype": "text/x-python", 271 | "name": "python", 272 | "nbconvert_exporter": "python", 273 | "pygments_lexer": "ipython3", 274 | "version": "3.12.0" 275 | } 276 | }, 277 | "nbformat": 4, 278 | "nbformat_minor": 5 279 | } 280 | -------------------------------------------------------------------------------- /cheatsheet.20.Dataclasses.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "677bc4b3", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Dataclasses\n", 9 | "\n", 10 | "`Dataclasses` are python classes, but are suited for storing data objects. This module provides a decorator and functions for automatically adding generated special methods such as `__init__()` and `__repr__()` to user-defined classes.\n", 11 | "\n", 12 | "## Features\n", 13 | "\n", 14 | "1. They store data and represent a certain data type. Ex: A number. For people familiar with ORMs, a model instance is a data object. It represents a specific kind of entity. It holds attributes that define or represent the entity.\n", 15 | "2. They can be compared to other objects of the same type. Ex: A number can be greater than, less than, or equal to another number.\n", 16 | "\n", 17 | "Python 3.7 provides a decorator dataclass that is used to convert a class into a dataclass." 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": null, 23 | "id": "db33b156", 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "class Number:\n", 28 | " def __init__(self, val):\n", 29 | " self.val = val\n", 30 | "\n", 31 | "obj = Number(2)\n", 32 | "obj.val\n", 33 | "# 2" 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "id": "b2fcac23", 39 | "metadata": {}, 40 | "source": [ 41 | "with dataclass" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "id": "014bc3cd", 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "from dataclasses import dataclass\n", 52 | "\n", 53 | "@dataclass\n", 54 | "class Number:\n", 55 | " val: int\n", 56 | "\n", 57 | "obj = Number(2)\n", 58 | "obj.val\n", 59 | "# 2" 60 | ] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "id": "dd21faa2", 65 | "metadata": {}, 66 | "source": [ 67 | "## Default values\n", 68 | "\n", 69 | "It is easy to add default values to the fields of your data class." 70 | ] 71 | }, 72 | { 73 | "cell_type": "code", 74 | "execution_count": null, 75 | "id": "589370dd-5ca1-46ad-a561-b7dc74dae748", 76 | "metadata": {}, 77 | "outputs": [], 78 | "source": [ 79 | "from dataclasses import dataclass\n", 80 | "\n", 81 | "@dataclass\n", 82 | "class Product:\n", 83 | " name: str\n", 84 | " count: int = 0\n", 85 | " price: float = 0.0\n", 86 | "\n", 87 | "obj = Product(\"Python\")" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": null, 93 | "id": "28d26f97-28a1-4441-a1c2-f0aacb077943", 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "obj.name\n", 98 | "# Python" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "id": "6e4d1ecc-c441-4e07-99ee-770f291a4543", 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "obj.count\n", 109 | "# 0" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "id": "3c5b788d-08d6-4efd-91e3-fe1fab765a40", 116 | "metadata": {}, 117 | "outputs": [], 118 | "source": [ 119 | "obj.price\n", 120 | "# 0.0" 121 | ] 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "id": "feb8322b", 126 | "metadata": {}, 127 | "source": [ 128 | "## Type hints\n", 129 | "\n", 130 | "It is mandatory to define the data type in dataclass. However, If you would rather not specify the datatype then, use `typing.Any`." 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": null, 136 | "id": "c987ec3d-bbca-467e-923f-3cfb38ed861e", 137 | "metadata": {}, 138 | "outputs": [], 139 | "source": [ 140 | "from dataclasses import dataclass\n", 141 | "from typing import Any\n", 142 | "\n", 143 | "@dataclass\n", 144 | "class WithoutExplicitTypes:\n", 145 | " name: Any\n", 146 | " value: Any = 42" 147 | ] 148 | } 149 | ], 150 | "metadata": { 151 | "kernelspec": { 152 | "display_name": "Python 3 (ipykernel)", 153 | "language": "python", 154 | "name": "python3" 155 | }, 156 | "language_info": { 157 | "codemirror_mode": { 158 | "name": "ipython", 159 | "version": 3 160 | }, 161 | "file_extension": ".py", 162 | "mimetype": "text/x-python", 163 | "name": "python", 164 | "nbconvert_exporter": "python", 165 | "pygments_lexer": "ipython3", 166 | "version": "3.12.0" 167 | } 168 | }, 169 | "nbformat": 4, 170 | "nbformat_minor": 5 171 | } 172 | -------------------------------------------------------------------------------- /cheatsheet.21.setup.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "e88229b2", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python setup.py\n", 9 | "\n", 10 | "A 'controversial' opinion\n", 11 | "\n", 12 | "Using `setup.py` to pack and distribute your python packages can be quite challenging every so often. Tools like [Poetry](https://python-poetry.org/) make not only the packaging a **lot easier**, but also help you to manage your dependencies in a very convenient way.\n", 13 | "\n", 14 | "If you want more information about Poetry you can read the following articles:\n", 15 | "\n", 16 | "- [Python projects with Poetry and VSCode. Part 1](https://www.pythoncheatsheet.org/blog/python-projects-with-poetry-and-vscode-part-1)\n", 17 | "- [Python projects with Poetry and VSCode. Part 2](https://www.pythoncheatsheet.org/blog/python-projects-with-poetry-and-vscode-part-2)\n", 18 | "- [Python projects with Poetry and VSCode. Part 3](https://www.pythoncheatsheet.org/blog/python-projects-with-poetry-and-vscode-part-3)\n", 19 | "\n", 20 | "## Introduction\n", 21 | "\n", 22 | "The setup script is the center of all activity in building, distributing, and installing modules using the Distutils. The main purpose of the setup script is to describe your module distribution to the Distutils, so that the various commands that operate on your modules do the right thing.\n", 23 | "\n", 24 | "The `setup.py` file is at the heart of a Python project. It describes all the metadata about your project. There are quite a few fields you can add to a project to give it a rich set of metadata describing the project. However, there are only three required fields: name, version, and packages. The name field must be unique if you wish to publish your package on the Python Package Index (PyPI). The version field keeps track of different releases of the project. The package’s field describes where you’ve put the Python source code within your project.\n", 25 | "\n", 26 | "This allows you to easily install Python packages. Often it’s enough to write:" 27 | ] 28 | }, 29 | { 30 | "cell_type": "code", 31 | "execution_count": null, 32 | "id": "ba6e17ba", 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "%%bash\n", 37 | "python setup.py install" 38 | ] 39 | }, 40 | { 41 | "cell_type": "markdown", 42 | "id": "6e437b70", 43 | "metadata": {}, 44 | "source": [ 45 | "and module will install itself.\n", 46 | "\n", 47 | "## Example\n", 48 | "\n", 49 | "Our initial setup.py will also include information about the license and will re-use the README.txt file for the long_description field. This will look like:" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": null, 55 | "id": "4200c443", 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "from distutils.core import setup\n", 60 | "setup(\n", 61 | " name='pythonCheatsheet',\n", 62 | " version='0.1',\n", 63 | " packages=['pipenv',],\n", 64 | " license='MIT',\n", 65 | " long_description=open('README.txt').read(),\n", 66 | ")" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "id": "2e38d90b", 72 | "metadata": {}, 73 | "source": [ 74 | "Find more information visit the [official documentation](http://docs.python.org/install/index.html)." 75 | ] 76 | } 77 | ], 78 | "metadata": { 79 | "kernelspec": { 80 | "display_name": "Python 3 (ipykernel)", 81 | "language": "python", 82 | "name": "python3" 83 | }, 84 | "language_info": { 85 | "codemirror_mode": { 86 | "name": "ipython", 87 | "version": 3 88 | }, 89 | "file_extension": ".py", 90 | "mimetype": "text/x-python", 91 | "name": "python", 92 | "nbconvert_exporter": "python", 93 | "pygments_lexer": "ipython3", 94 | "version": "3.12.0" 95 | } 96 | }, 97 | "nbformat": 4, 98 | "nbformat_minor": 5 99 | } 100 | -------------------------------------------------------------------------------- /cheatsheet.22.Main.top-level.script.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "0ba653e8", 6 | "metadata": {}, 7 | "source": [ 8 | "# Main top-level script environment\n", 9 | "\n", 10 | "## What is it\n", 11 | "\n", 12 | "`__main__` is the name of the scope in which top-level code executes. A module’s **name** is set equal to `__main__` when read from standard input, a script, or from an interactive prompt.\n", 13 | "\n", 14 | "A module can discover whether it is running in the main scope by checking its own `__name__`, which allows a common idiom for conditionally executing code in a module. When it is run as a script or with `python -m` but not when it is imported:" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "id": "b591901b", 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "if __name__ == \"__main__\":\n", 25 | "# execute only if run as a script\n", 26 | "main()" 27 | ] 28 | }, 29 | { 30 | "cell_type": "markdown", 31 | "id": "1952934b", 32 | "metadata": {}, 33 | "source": [ 34 | "For a package, the same effect can be achieved by including a **main**.py module, the contents of which will be executed when the module is run with -m.\n", 35 | "\n", 36 | "For example, we are developing a script designed to be used as a module, we should do:" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "id": "aa903da3", 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "def add(a, b):\n", 47 | " return a+b\n", 48 | "\n", 49 | "if __name__ == \"__main__\":\n", 50 | "add(3, 5)" 51 | ] 52 | }, 53 | { 54 | "cell_type": "markdown", 55 | "id": "2e307e17", 56 | "metadata": {}, 57 | "source": [ 58 | "## Advantages\n", 59 | "\n", 60 | "1. Every Python module has it’s `__name__` defined and if this is `__main__`, it implies that the module is run standalone by the user, and we can do corresponding appropriate actions.\n", 61 | "2. If you import this script as a module in another script, the **name** is set to the name of the script/module.\n", 62 | "3. Python files can act as either reusable modules, or as standalone programs.\n", 63 | "4. if `__name__ == “main”:` is used to execute some code only if the file run directly, and is not being imported." 64 | ] 65 | } 66 | ], 67 | "metadata": { 68 | "kernelspec": { 69 | "display_name": "Python 3 (ipykernel)", 70 | "language": "python", 71 | "name": "python3" 72 | }, 73 | "language_info": { 74 | "codemirror_mode": { 75 | "name": "ipython", 76 | "version": 3 77 | }, 78 | "file_extension": ".py", 79 | "mimetype": "text/x-python", 80 | "name": "python", 81 | "nbconvert_exporter": "python", 82 | "pygments_lexer": "ipython3", 83 | "version": "3.12.0" 84 | } 85 | }, 86 | "nbformat": 4, 87 | "nbformat_minor": 5 88 | } 89 | -------------------------------------------------------------------------------- /cheatsheet.23.Virtual.Environment.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "964b8d62", 6 | "metadata": {}, 7 | "source": [ 8 | "# Virtual Environment\n", 9 | "\n", 10 | "The use of a Virtual Environment is to test python code in encapsulated environments, and to also avoid filling the base Python installation with libraries we might use for only one project.\n", 11 | "\n", 12 | "## virtualenv\n", 13 | "\n", 14 | "1. Install virtualenv\n", 15 | "\n", 16 | " ```\n", 17 | " pip install virtualenv\n", 18 | " ```\n", 19 | "\n", 20 | "2. Install virtualenvwrapper-win (Windows)\n", 21 | "\n", 22 | " ```\n", 23 | " pip install virtualenvwrapper-win\n", 24 | " ```\n", 25 | "\n", 26 | "Usage:\n", 27 | "\n", 28 | "1. Make a Virtual Environment named `HelloWorld`\n", 29 | "\n", 30 | " ```\n", 31 | " mkvirtualenv HelloWorld\n", 32 | " ```\n", 33 | "\n", 34 | " Anything we install now will be specific to this project. And available to the projects we connect to this environment.\n", 35 | "\n", 36 | "2. Set Project Directory\n", 37 | "\n", 38 | " To bind our virtualenv with our current working directory we simply enter:\n", 39 | "\n", 40 | " ```\n", 41 | " setprojectdir .\n", 42 | " ```\n", 43 | "\n", 44 | "3. Deactivate\n", 45 | "\n", 46 | " To move onto something else in the command line type `deactivate` to deactivate your environment.\n", 47 | "\n", 48 | " ```\n", 49 | " deactivate\n", 50 | " ```\n", 51 | "\n", 52 | " Notice how the parenthesis disappear.\n", 53 | "\n", 54 | "4. Workon\n", 55 | "\n", 56 | " Open up the command prompt and type `workon HelloWorld` to activate the environment and move into your root project folder\n", 57 | "\n", 58 | " ```\n", 59 | " workon HelloWorld\n", 60 | " ```\n", 61 | "\n", 62 | "## Poetry\n", 63 | "\n", 64 | "\n", 65 | "\n", 66 | "From [Poetry website](https://python-poetry.org/)\n", 67 | "\n", 68 | "Poetry is a tool for dependency management and packaging in Python. It allows you to declare the libraries your project depends on and it will manage (install/update) them for you.\n", 69 | "\n", 70 | "1. Install Poetry\n", 71 | "\n", 72 | " ```\n", 73 | " pip install --user poetry\n", 74 | " ```\n", 75 | "\n", 76 | "2. Create a new project\n", 77 | "\n", 78 | " ```\n", 79 | " poetry new my-project\n", 80 | " ```\n", 81 | "\n", 82 | " This will create a my-project directory:\n", 83 | "\n", 84 | " ```\n", 85 | " my-project\n", 86 | " ├── pyproject.toml\n", 87 | " ├── README.rst\n", 88 | " ├── poetry_demo\n", 89 | " │ └── __init__.py\n", 90 | " └── tests\n", 91 | " ├── __init__.py\n", 92 | " └── test_poetry_demo.py\n", 93 | " ```\n", 94 | "\n", 95 | " The pyproject.toml file will orchestrate your project and its dependencies:\n", 96 | "\n", 97 | " ```\n", 98 | " [tool.poetry]\n", 99 | " name = \"my-project\"\n", 100 | " version = \"0.1.0\"\n", 101 | " description = \"\"\n", 102 | " authors = [\"your name \"]\n", 103 | " \n", 104 | " [tool.poetry.dependencies]\n", 105 | " python = \"*\"\n", 106 | " \n", 107 | " [tool.poetry.dev-dependencies]\n", 108 | " pytest = \"^3.4\"\n", 109 | " ```\n", 110 | "\n", 111 | "3. Packages\n", 112 | "\n", 113 | " To add dependencies to your project, you can specify them in the tool.poetry.dependencies section:\n", 114 | "\n", 115 | " ```\n", 116 | " [tool.poetry.dependencies]\n", 117 | " pendulum = \"^1.4\"\n", 118 | " ```\n", 119 | "\n", 120 | " Also, instead of modifying the pyproject.toml file by hand, you can use the add command and it will automatically find a suitable version constraint.\n", 121 | "\n", 122 | " ```\n", 123 | " $ poetry add pendulum\n", 124 | " ```\n", 125 | "\n", 126 | " To install the dependencies listed in the pyproject.toml:\n", 127 | "\n", 128 | " ```\n", 129 | " poetry install\n", 130 | " ```\n", 131 | "\n", 132 | " To remove dependencies:\n", 133 | "\n", 134 | " ```\n", 135 | " poetry remove pendulum\n", 136 | " ```\n", 137 | "\n", 138 | "For more information, check the [documentation](https://poetry.eustace.io/docs/) or read here:\n", 139 | "\n", 140 | "- [Python projects with Poetry and VSCode. Part 1](https://www.pythoncheatsheet.org/blog/python-projects-with-poetry-and-vscode-part-1)\n", 141 | "- [Python projects with Poetry and VSCode. Part 2](https://www.pythoncheatsheet.org/blog/python-projects-with-poetry-and-vscode-part-2)\n", 142 | "- [Python projects with Poetry and VSCode. Part 3](https://www.pythoncheatsheet.org/blog/python-projects-with-poetry-and-vscode-part-3)\n", 143 | "\n", 144 | "## Pipenv\n", 145 | "\n", 146 | "\n", 147 | "\n", 148 | "From [Pipenv website](https://pipenv.pypa.io/en/latest/)\n", 149 | "\n", 150 | "Pipenv is a tool that aims to bring the best of all packaging worlds (bundler, composer, npm, cargo, yarn, etc.) to the Python world. Windows is a first-class citizen, in our world.\n", 151 | "\n", 152 | "1. Install pipenv\n", 153 | "\n", 154 | " ```\n", 155 | " pip install pipenv\n", 156 | " ```\n", 157 | "\n", 158 | "2. Enter your Project directory and install the Packages for your project\n", 159 | "\n", 160 | " ```\n", 161 | " cd my_project\n", 162 | " pipenv install \n", 163 | " ```\n", 164 | "\n", 165 | " Pipenv will install your package and create a Pipfile for you in your project’s directory. The Pipfile is used to track which dependencies your project needs in case you need to re-install them.\n", 166 | "\n", 167 | "3. Uninstall Packages\n", 168 | "\n", 169 | " ```\n", 170 | " pipenv uninstall \n", 171 | " ```\n", 172 | "\n", 173 | "4. Activate the Virtual Environment associated with your Python project\n", 174 | "\n", 175 | " ```\n", 176 | " pipenv shell\n", 177 | " ```\n", 178 | "\n", 179 | "5. Exit the Virtual Environment\n", 180 | "\n", 181 | " ```\n", 182 | " exit\n", 183 | " ```\n", 184 | "\n", 185 | "Find more information and a video in [docs.pipenv.org](https://docs.pipenv.org/).\n", 186 | "\n", 187 | "## Anaconda\n", 188 | "\n", 189 | "\n", 190 | "\n", 191 | "[Anaconda](https://anaconda.com/) is another popular tool to manage python packages.\n", 192 | "\n", 193 | "Where packages, notebooks, projects and environments are shared. Your place for free public conda package hosting.\n", 194 | "\n", 195 | "Usage:\n", 196 | "\n", 197 | "1. Make a Virtual Environment\n", 198 | "\n", 199 | " ```\n", 200 | " conda create -n HelloWorld\n", 201 | " ```\n", 202 | "\n", 203 | "2. To use the Virtual Environment, activate it by:\n", 204 | "\n", 205 | " ```\n", 206 | " conda activate HelloWorld\n", 207 | " ```\n", 208 | "\n", 209 | " Anything installed now will be specific to the project HelloWorld\n", 210 | "\n", 211 | "3. Exit the Virtual Environment\n", 212 | "\n", 213 | " ```\n", 214 | " conda deactivate\n", 215 | " ```" 216 | ] 217 | } 218 | ], 219 | "metadata": { 220 | "kernelspec": { 221 | "display_name": "Python 3 (ipykernel)", 222 | "language": "python", 223 | "name": "python3" 224 | }, 225 | "language_info": { 226 | "codemirror_mode": { 227 | "name": "ipython", 228 | "version": 3 229 | }, 230 | "file_extension": ".py", 231 | "mimetype": "text/x-python", 232 | "name": "python", 233 | "nbconvert_exporter": "python", 234 | "pygments_lexer": "ipython3", 235 | "version": "3.12.0" 236 | } 237 | }, 238 | "nbformat": 4, 239 | "nbformat_minor": 5 240 | } 241 | -------------------------------------------------------------------------------- /standard.library.01.Copy.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "e0ef2781", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Copy Module\n", 9 | "\n", 10 | "Copy Module is a set of functions that are related to copying different elements of a list, objects, arrays, etc. It can be used to create shallow copies as well as deep copies.\n", 11 | "\n", 12 | "From the Python 3 [documentation](https://docs.python.org/3/library/copy.html)\n", 13 | "\n", 14 | "Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic **shallow** and **deep** copy operations.\n", 15 | "\n", 16 | "## Shallow copy operations\n", 17 | "\n", 18 | "Shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.\n", 19 | "\n", 20 | "copy.copy(x) Return a shallow copy of x." 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "id": "5e30dd96-6ce9-497c-a080-ba29f988f0b2", 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "import copy\n", 31 | "a = [[1],[2],[3]]\n", 32 | "b = copy.copy(a) ## this will copy the list a to list b" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": null, 38 | "id": "9ca4cce2-f213-4541-a136-d0e1e6830467", 39 | "metadata": {}, 40 | "outputs": [], 41 | "source": [ 42 | "a\n", 43 | "#[[1], [2], [3]]" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "id": "3a740bd4-d999-43c4-b279-b58a50790ba6", 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "b\n", 54 | "#[[1], [2], [3]]" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "id": "6068bf5e", 60 | "metadata": {}, 61 | "source": [ 62 | "### Without importing copy module you can’t use it" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": null, 68 | "id": "0609394e", 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "# Traceback (most recent call last):\n", 73 | "# File \"\", line 1, in \n", 74 | "# NameError: name 'copy' is not defined" 75 | ] 76 | }, 77 | { 78 | "cell_type": "markdown", 79 | "id": "3be7765e", 80 | "metadata": {}, 81 | "source": [ 82 | "## Deep copy operations\n", 83 | "\n", 84 | "A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.\n", 85 | "\n", 86 | "copy.deepcopy(x[, memo]) Return a deep copy of x." 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "id": "1c13b5b8-a1ec-4425-b7b2-6a1bed5385e2", 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "import copy\n", 97 | "a = [[1],[2],[3]]\n", 98 | "b = copy.deepcopy(a) ## this will copy the list a to list b" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "id": "05cc173d-26c5-4d12-8aa6-667676dcf346", 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "a[0][0] = 0\n", 109 | "a[1] = None" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "id": "021d640d-ed52-4d92-a140-288a137c9722", 116 | "metadata": {}, 117 | "outputs": [], 118 | "source": [ 119 | "a\n", 120 | "#[[0], None, [3]]" 121 | ] 122 | }, 123 | { 124 | "cell_type": "code", 125 | "execution_count": null, 126 | "id": "058d5457-ff8c-4f0c-8a89-ae3ef81b9f34", 127 | "metadata": {}, 128 | "outputs": [], 129 | "source": [ 130 | "b\n", 131 | "#[[1], [2], [3]]" 132 | ] 133 | } 134 | ], 135 | "metadata": { 136 | "kernelspec": { 137 | "display_name": "Python 3 (ipykernel)", 138 | "language": "python", 139 | "name": "python3" 140 | }, 141 | "language_info": { 142 | "codemirror_mode": { 143 | "name": "ipython", 144 | "version": 3 145 | }, 146 | "file_extension": ".py", 147 | "mimetype": "text/x-python", 148 | "name": "python", 149 | "nbconvert_exporter": "python", 150 | "pygments_lexer": "ipython3", 151 | "version": "3.12.0" 152 | } 153 | }, 154 | "nbformat": 4, 155 | "nbformat_minor": 5 156 | } 157 | -------------------------------------------------------------------------------- /standard.library.04.Json.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "15b9ecda", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Json Module\n", 9 | "\n", 10 | "JSON stands for JavaScript Object Notation and is a lightweight format for storing and transporting data. JSON is often used when data is sent from a server to a web page.\n", 11 | "\n", 12 | "Python has the built-in module `json`, which allow us to work with JSON data." 13 | ] 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": null, 18 | "id": "211752c8", 19 | "metadata": {}, 20 | "outputs": [], 21 | "source": [ 22 | "import json" 23 | ] 24 | }, 25 | { 26 | "cell_type": "markdown", 27 | "id": "4bf56c40", 28 | "metadata": {}, 29 | "source": [ 30 | "## JSON Data Types\n", 31 | "\n", 32 | "A JSON object is similar to a Python dictionary, but has the following differences:\n", 33 | "\n", 34 | "- JSON Keys are always string.\n", 35 | "- Strings are always enclosed with double quotes.\n", 36 | "- A JSON boolean start with lowercase letters.\n", 37 | "- `null` is the JSON equivalent of Python `None`.\n", 38 | "\n", 39 | "The data types JSON supports are:\n", 40 | "\n", 41 | "- String\n", 42 | "- Number\n", 43 | "- boolean\n", 44 | "- null\n", 45 | "- Object\n", 46 | "- Array\n", 47 | "\n", 48 | "Example:\n", 49 | "```json\n", 50 | "{\n", 51 | " \"name\": \"Charles\",\n", 52 | " \"age\": 33,\n", 53 | " \"has_hair\": false,\n", 54 | " \"hobbies\": [\"photography\", \"running\"],\n", 55 | " \"appearance\": {\n", 56 | " \"eyes\": \"brown\",\n", 57 | " \"hair_color\": null\n", 58 | " }\n", 59 | "}\n", 60 | "```" 61 | ] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "id": "ac6f2fb7", 66 | "metadata": {}, 67 | "source": [ 68 | "## JSON loads() method\n", 69 | "\n", 70 | "With the `json.loads` method, you can parse a JSON object and transform it to a Python dictionary:" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": null, 76 | "id": "daf6b4cb-d297-4ad2-9869-db88a8f1452e", 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "import json" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "id": "d55b776e-828b-45c8-8e43-f839a321e775", 87 | "metadata": {}, 88 | "outputs": [], 89 | "source": [ 90 | "json_person = '{\"name\": \"Charles\", \"age\": 33, \"has_hair\": false, \"hobbies\": [\"photography\", \"running\"]}'\n", 91 | "python_person = json.loads(json_person)\n", 92 | "python_person\n", 93 | "# {'name': 'Charles', 'age': 33, 'has_hair': False, 'hobbies': ['photography', 'running']}" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "id": "abbfa16f-0350-4a58-bce7-f20b7f661b99", 100 | "metadata": {}, 101 | "outputs": [], 102 | "source": [ 103 | "type(python_person)\n", 104 | "# dict" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": null, 110 | "id": "e0ddcd90-7f05-41a2-9e44-1646055e35ae", 111 | "metadata": {}, 112 | "outputs": [], 113 | "source": [ 114 | "python_person.get(\"name\")\n", 115 | "# 'Charles'" 116 | ] 117 | }, 118 | { 119 | "cell_type": "markdown", 120 | "id": "8084f703", 121 | "metadata": {}, 122 | "source": [ 123 | "## JSON dumps() method\n", 124 | "\n", 125 | "The other way around. The `dumps()` method transforms a Python object to a JSON string:" 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": null, 131 | "id": "d0210d09-5b16-46ca-a5b9-4f900527517c", 132 | "metadata": {}, 133 | "outputs": [], 134 | "source": [ 135 | "import json" 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": null, 141 | "id": "5715b609-44f5-4b53-88f2-05e4ccfe5fd1", 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [ 145 | "python_person = {'name': 'Charles', 'age': 33, 'has_hair': False, 'hobbies': ['photography', 'running']}\n", 146 | "json_person = json.dumps(python_person)" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": null, 152 | "id": "f58c7554-1f91-4724-9e48-ba1516de3e08", 153 | "metadata": {}, 154 | "outputs": [], 155 | "source": [ 156 | "json_person\n", 157 | "# '{\"name\": \"Charles\", \"age\": 33, \"has_hair\": false, \"hobbies\": [\"photography\", \"running\"]}'" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": null, 163 | "id": "c7bc2dde-0fa9-4005-806d-3b4f0f27a04d", 164 | "metadata": {}, 165 | "outputs": [], 166 | "source": [ 167 | "type(json_person)\n", 168 | "# str" 169 | ] 170 | }, 171 | { 172 | "cell_type": "markdown", 173 | "id": "21b7ee92", 174 | "metadata": {}, 175 | "source": [ 176 | "## Reading and writing Json Files\n", 177 | "\n", 178 | "### Reading a Json File" 179 | ] 180 | }, 181 | { 182 | "cell_type": "code", 183 | "execution_count": null, 184 | "id": "ec08e47d", 185 | "metadata": {}, 186 | "outputs": [], 187 | "source": [ 188 | "import json\n", 189 | "\n", 190 | "with open(\"filename.json\", \"r\") as f:\n", 191 | " json_content = json.loads(f.read())\n", 192 | "\n", 193 | "json.loads(json_content)\n", 194 | "# {'name': 'Charles', 'age': 33, 'has_hair': False}" 195 | ] 196 | }, 197 | { 198 | "cell_type": "markdown", 199 | "id": "fc10ba60", 200 | "metadata": {}, 201 | "source": [ 202 | "### Writing a Json File" 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "execution_count": null, 208 | "id": "93228678-75a2-4a59-8320-611c72a71530", 209 | "metadata": {}, 210 | "outputs": [], 211 | "source": [ 212 | "import json\n", 213 | "\n", 214 | "person = {'name': 'Charles', 'age': 33}\n", 215 | "\n", 216 | "with open(\"filename.json\", \"w\") as f:\n", 217 | " f.write(json.dumps(person))" 218 | ] 219 | } 220 | ], 221 | "metadata": { 222 | "kernelspec": { 223 | "display_name": "Python 3 (ipykernel)", 224 | "language": "python", 225 | "name": "python3" 226 | }, 227 | "language_info": { 228 | "codemirror_mode": { 229 | "name": "ipython", 230 | "version": 3 231 | }, 232 | "file_extension": ".py", 233 | "mimetype": "text/x-python", 234 | "name": "python", 235 | "nbconvert_exporter": "python", 236 | "pygments_lexer": "ipython3", 237 | "version": "3.12.0" 238 | } 239 | }, 240 | "nbformat": 4, 241 | "nbformat_minor": 5 242 | } 243 | -------------------------------------------------------------------------------- /standard.library.05.Os.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "aacb625e", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Os Module\n", 9 | "\n", 10 | "This module provides a portable way of using operating system dependent functionality.\n", 11 | "\n", 12 | "Pathlib vs Os Module\n", 13 | "\n", 14 | "The [pathlib](https://www.pythoncheatsheet.org/modules/pathlib-module) module provides a lot more functionality than the ones listed here, like getting file name, getting file extension, reading/writing a file without manually opening it, etc. See the [official documentation](https://docs.python.org/3/library/pathlib.html) if you intend to know more.\n", 15 | "\n", 16 | "## Linux and Windows Paths\n", 17 | "\n", 18 | "On Windows, paths are written using backslashes (`\\`) as the separator between folder names. On Unix based operating system such as macOS, Linux, and BSDs, the forward slash (`/`) is used as the path separator. Joining paths can be a headache if your code needs to work on different platforms.\n", 19 | "\n", 20 | "Fortunately, Python provides us with `os.path.join` to handle this." 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "id": "a1e38cb4", 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "import os\n", 31 | "\n", 32 | "os.path.join('usr', 'bin', 'spam')\n", 33 | "# 'usr\\\\bin\\\\spam'" 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "id": "56de319d", 39 | "metadata": {}, 40 | "source": [ 41 | "Joining paths is helpful if you need to create different file paths under the same directory." 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "id": "bd38d139", 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "my_files = ['accounts.txt', 'details.csv', 'invite.docx']\n", 52 | "\n", 53 | "for filename in my_files:\n", 54 | " print(os.path.join('C:\\\\Users\\\\asweigart', filename))\n", 55 | "\n", 56 | "# C:\\Users\\docs\\accounts.txt\n", 57 | "# C:\\Users\\docs\\details.csv\n", 58 | "# C:\\Users\\docs\\invite.docx" 59 | ] 60 | }, 61 | { 62 | "cell_type": "markdown", 63 | "id": "912abd16", 64 | "metadata": {}, 65 | "source": [ 66 | "## The current working directory" 67 | ] 68 | }, 69 | { 70 | "cell_type": "code", 71 | "execution_count": null, 72 | "id": "82a0de2f-bad0-4511-808e-2fbb355ba4ef", 73 | "metadata": {}, 74 | "outputs": [], 75 | "source": [ 76 | "import os" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": null, 82 | "id": "38efc1ec-c606-45ca-8bb4-b0ee01db477a", 83 | "metadata": {}, 84 | "outputs": [], 85 | "source": [ 86 | "os.getcwd()\n", 87 | "# 'C:\\\\Python34'" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": null, 93 | "id": "3ba223f8-5319-4781-b56e-963e0ce29d3a", 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "os.chdir('C:\\\\Windows\\\\System32')\n", 98 | "os.getcwd()\n", 99 | "# 'C:\\\\Windows\\\\System32'" 100 | ] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "id": "2bfeba88", 105 | "metadata": {}, 106 | "source": [ 107 | "## Creating new folders" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": null, 113 | "id": "4dcb8e20", 114 | "metadata": {}, 115 | "outputs": [], 116 | "source": [ 117 | "import os\n", 118 | "os.makedirs('C:\\\\delicious\\\\walnut\\\\waffles')" 119 | ] 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "id": "f31c12e8", 124 | "metadata": {}, 125 | "source": [ 126 | "## Absolute vs. Relative paths\n", 127 | "\n", 128 | "There are two ways to specify a file path.\n", 129 | "\n", 130 | "- An **absolute path**, which always begins with the root folder\n", 131 | "- A **relative path**, which is relative to the program’s current working directory\n", 132 | "\n", 133 | "There are also the dot (`.`) and dot-dot (`..`) folders. These are not real folders, but special names that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this directory.” Two periods (“dot-dot”) means “the parent folder.”\n", 134 | "\n", 135 | "### Handling Absolute paths\n", 136 | "\n", 137 | "To see if a path is an absolute path:" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "id": "4ad6dfea-9fa5-4f9b-8b89-3bc8c86bab94", 144 | "metadata": {}, 145 | "outputs": [], 146 | "source": [ 147 | "import os" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": null, 153 | "id": "d22fbc9a-a83c-4419-b725-d0afce85f60e", 154 | "metadata": {}, 155 | "outputs": [], 156 | "source": [ 157 | "os.path.isabs('/')\n", 158 | "# True" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": null, 164 | "id": "47cde54b-a472-44ec-947f-2b32ec7bcd06", 165 | "metadata": {}, 166 | "outputs": [], 167 | "source": [ 168 | "os.path.isabs('..')\n", 169 | "# False" 170 | ] 171 | }, 172 | { 173 | "cell_type": "markdown", 174 | "id": "1a25b9bf", 175 | "metadata": {}, 176 | "source": [ 177 | "You can also extract an absolute path:" 178 | ] 179 | }, 180 | { 181 | "cell_type": "code", 182 | "execution_count": null, 183 | "id": "49f6e350-bacd-4a93-852f-1371bcd74f96", 184 | "metadata": {}, 185 | "outputs": [], 186 | "source": [ 187 | "import os" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": null, 193 | "id": "e4d9476a-c287-4fa5-8505-cbc48408ed20", 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [ 197 | "os.getcwd()\n", 198 | "'/home/docs'" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": null, 204 | "id": "aa276a8a-65e7-4629-abaa-92b825fab668", 205 | "metadata": {}, 206 | "outputs": [], 207 | "source": [ 208 | "os.path.abspath('..')\n", 209 | "'/home'" 210 | ] 211 | }, 212 | { 213 | "cell_type": "markdown", 214 | "id": "d6686b06", 215 | "metadata": {}, 216 | "source": [ 217 | "### Handling Relative paths\n", 218 | "\n", 219 | "You can get a relative path from a starting path to another path." 220 | ] 221 | }, 222 | { 223 | "cell_type": "code", 224 | "execution_count": null, 225 | "id": "d0f486b4", 226 | "metadata": {}, 227 | "outputs": [], 228 | "source": [ 229 | "import os\n", 230 | "os.path.relpath('/etc/passwd', '/')\n", 231 | "# 'etc/passwd'" 232 | ] 233 | }, 234 | { 235 | "cell_type": "markdown", 236 | "id": "742b6be5", 237 | "metadata": {}, 238 | "source": [ 239 | "## Path and File validity\n", 240 | "\n", 241 | "### Checking if a file/directory exists" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": null, 247 | "id": "bbedb161-5bc1-4faf-ae2e-39f124e0aa0f", 248 | "metadata": {}, 249 | "outputs": [], 250 | "source": [ 251 | "import os" 252 | ] 253 | }, 254 | { 255 | "cell_type": "code", 256 | "execution_count": null, 257 | "id": "22c3d378-9aa6-47e8-8e43-6a79c0420a33", 258 | "metadata": {}, 259 | "outputs": [], 260 | "source": [ 261 | "os.path.exists('.')\n", 262 | "# True" 263 | ] 264 | }, 265 | { 266 | "cell_type": "code", 267 | "execution_count": null, 268 | "id": "b8332163-2b46-496c-b918-e257f287cc30", 269 | "metadata": {}, 270 | "outputs": [], 271 | "source": [ 272 | "os.path.exists('setup.py')\n", 273 | "# True" 274 | ] 275 | }, 276 | { 277 | "cell_type": "code", 278 | "execution_count": null, 279 | "id": "566164fd-8986-4603-b999-3031406e2768", 280 | "metadata": {}, 281 | "outputs": [], 282 | "source": [ 283 | "os.path.exists('/etc')\n", 284 | "# True" 285 | ] 286 | }, 287 | { 288 | "cell_type": "code", 289 | "execution_count": null, 290 | "id": "7ce39b66-081f-4583-896f-a506cdbb2e6b", 291 | "metadata": {}, 292 | "outputs": [], 293 | "source": [ 294 | "os.path.exists('nonexistentfile')\n", 295 | "# False" 296 | ] 297 | }, 298 | { 299 | "cell_type": "markdown", 300 | "id": "8d5d7856", 301 | "metadata": {}, 302 | "source": [ 303 | "### Checking if a path is a file" 304 | ] 305 | }, 306 | { 307 | "cell_type": "code", 308 | "execution_count": null, 309 | "id": "e83e32cc-5a1e-4d0f-b2f5-a6a81bd9f2d7", 310 | "metadata": {}, 311 | "outputs": [], 312 | "source": [ 313 | "import os" 314 | ] 315 | }, 316 | { 317 | "cell_type": "code", 318 | "execution_count": null, 319 | "id": "9317830c-9496-46c9-b6a8-aedccd6921e0", 320 | "metadata": {}, 321 | "outputs": [], 322 | "source": [ 323 | "os.path.isfile('setup.py')\n", 324 | "# True" 325 | ] 326 | }, 327 | { 328 | "cell_type": "code", 329 | "execution_count": null, 330 | "id": "9850aa0c-39da-4d84-a363-c325f6ded852", 331 | "metadata": {}, 332 | "outputs": [], 333 | "source": [ 334 | "os.path.isfile('/home')\n", 335 | "# False" 336 | ] 337 | }, 338 | { 339 | "cell_type": "code", 340 | "execution_count": null, 341 | "id": "f29a2f10-b2bf-4129-a9f0-de642b2eff40", 342 | "metadata": {}, 343 | "outputs": [], 344 | "source": [ 345 | "os.path.isfile('nonexistentfile')\n", 346 | "# False" 347 | ] 348 | }, 349 | { 350 | "cell_type": "markdown", 351 | "id": "b0baa077", 352 | "metadata": {}, 353 | "source": [ 354 | "### Checking if a path is a directory" 355 | ] 356 | }, 357 | { 358 | "cell_type": "code", 359 | "execution_count": null, 360 | "id": "212c6d3c-5fb6-4577-8f76-7472d34bc937", 361 | "metadata": {}, 362 | "outputs": [], 363 | "source": [ 364 | "import os" 365 | ] 366 | }, 367 | { 368 | "cell_type": "code", 369 | "execution_count": null, 370 | "id": "5987ca1d-fa94-4cb3-a378-8e9e15b167b0", 371 | "metadata": {}, 372 | "outputs": [], 373 | "source": [ 374 | "os.path.isdir('/')\n", 375 | "# True" 376 | ] 377 | }, 378 | { 379 | "cell_type": "code", 380 | "execution_count": null, 381 | "id": "497d7546-3e4b-4c06-bd42-88958f851749", 382 | "metadata": {}, 383 | "outputs": [], 384 | "source": [ 385 | "os.path.isdir('setup.py')\n", 386 | "# False" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": null, 392 | "id": "ab5bb6eb-a40d-4166-97b0-4d6fe5a5750f", 393 | "metadata": {}, 394 | "outputs": [], 395 | "source": [ 396 | "os.path.isdir('/spam')\n", 397 | "# False" 398 | ] 399 | }, 400 | { 401 | "cell_type": "markdown", 402 | "id": "f67ba6c5", 403 | "metadata": {}, 404 | "source": [ 405 | "## Getting a file’s size in bytes" 406 | ] 407 | }, 408 | { 409 | "cell_type": "code", 410 | "execution_count": null, 411 | "id": "18c48c75", 412 | "metadata": {}, 413 | "outputs": [], 414 | "source": [ 415 | "import os\n", 416 | "\n", 417 | "os.path.getsize('C:\\\\Windows\\\\System32\\\\calc.exe')\n", 418 | "# 776192" 419 | ] 420 | }, 421 | { 422 | "cell_type": "markdown", 423 | "id": "307118a2", 424 | "metadata": {}, 425 | "source": [ 426 | "## Listing directories" 427 | ] 428 | }, 429 | { 430 | "cell_type": "code", 431 | "execution_count": null, 432 | "id": "9cbcf348", 433 | "metadata": {}, 434 | "outputs": [], 435 | "source": [ 436 | "import os\n", 437 | "\n", 438 | "os.listdir('C:\\\\Windows\\\\System32')\n", 439 | "# ['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',\n", 440 | "# --snip--\n", 441 | "# 'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']" 442 | ] 443 | }, 444 | { 445 | "cell_type": "markdown", 446 | "id": "0d4f33c8", 447 | "metadata": {}, 448 | "source": [ 449 | "## Directory file sizes\n", 450 | "\n", 451 | "\n", 452 | "\n", 453 | "WARNING\n", 454 | "\n", 455 | "Directories themselves also have a size! So, you might want to check for whether a path is a file or directory using the methods in the methods discussed in the above section." 456 | ] 457 | }, 458 | { 459 | "cell_type": "code", 460 | "execution_count": null, 461 | "id": "de95baf7", 462 | "metadata": {}, 463 | "outputs": [], 464 | "source": [ 465 | "import os\n", 466 | "total_size = 0\n", 467 | "\n", 468 | "for filename in os.listdir('C:\\\\Windows\\\\System32'):\n", 469 | " total_size = total_size + os.path.getsize(os.path.join('C:\\\\Windows\\\\System32', filename))\n", 470 | "\n", 471 | "print(total_size)\n", 472 | "# 1117846456" 473 | ] 474 | }, 475 | { 476 | "cell_type": "markdown", 477 | "id": "d0206d9b", 478 | "metadata": {}, 479 | "source": [ 480 | "## Deleting files and folders\n", 481 | "\n", 482 | "- Calling `os.unlink(path)` will delete the file at path.\n", 483 | "- Calling `os.rmdir(path)` will delete the folder at path. This folder must be empty of any files or folders.\n", 484 | "\n", 485 | "## Walking a Directory Tree\n", 486 | "\n" 487 | ] 488 | }, 489 | { 490 | "cell_type": "code", 491 | "execution_count": null, 492 | "id": "7ef3aa30-a91a-456d-8baf-a7f450fa0ccc", 493 | "metadata": {}, 494 | "outputs": [], 495 | "source": [ 496 | "import os\n", 497 | "\n", 498 | "for folder_name, subfolders, filenames in os.walk('C:\\\\delicious'):\n", 499 | " print(f'The current folder is {folder_name}')\n", 500 | " for subfolder in subfolders:\n", 501 | " print('SUBFOLDER OF {folder_name}: {subfolder}')\n", 502 | " for filename in filenames:\n", 503 | " print('FILE INSIDE {folder_name}: filename{filename}')\n", 504 | " print('')\n", 505 | "\n", 506 | "# The current folder is C:\\delicious\n", 507 | "# SUBFOLDER OF C:\\delicious: cats\n", 508 | "# SUBFOLDER OF C:\\delicious: walnut\n", 509 | "# FILE INSIDE C:\\delicious: spam.txt\n", 510 | "\n", 511 | "# The current folder is C:\\delicious\\cats\n", 512 | "# FILE INSIDE C:\\delicious\\cats: catnames.txt\n", 513 | "# FILE INSIDE C:\\delicious\\cats: zophie.jpg\n", 514 | "\n", 515 | "# The current folder is C:\\delicious\\walnut\n", 516 | "# SUBFOLDER OF C:\\delicious\\walnut: waffles\n", 517 | "\n", 518 | "# The current folder is C:\\delicious\\walnut\\waffles\n", 519 | "# FILE INSIDE C:\\delicious\\walnut\\waffles: butter.txt" 520 | ] 521 | } 522 | ], 523 | "metadata": { 524 | "kernelspec": { 525 | "display_name": "Python 3 (ipykernel)", 526 | "language": "python", 527 | "name": "python3" 528 | }, 529 | "language_info": { 530 | "codemirror_mode": { 531 | "name": "ipython", 532 | "version": 3 533 | }, 534 | "file_extension": ".py", 535 | "mimetype": "text/x-python", 536 | "name": "python", 537 | "nbconvert_exporter": "python", 538 | "pygments_lexer": "ipython3", 539 | "version": "3.12.0" 540 | } 541 | }, 542 | "nbformat": 4, 543 | "nbformat_minor": 5 544 | } 545 | -------------------------------------------------------------------------------- /standard.library.06.Pathlib.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "8d550839", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Pathlib Module\n", 9 | "\n", 10 | "The `pathlib` module was added in Python 3.4, offering an object-oriented way to handle file system paths.\n", 11 | "\n", 12 | "Pathlib vs Os Module\n", 13 | "\n", 14 | "`pathlib` provides a lot more functionality than the ones from `os` and listed here, like getting file name, getting file extension, reading/writing a file without manually opening it, etc. See the [official documentation](https://docs.python.org/3/library/pathlib.html) if you intend to know more.\n", 15 | "\n", 16 | "## Linux and Windows Paths\n", 17 | "\n", 18 | "On Windows, paths are written using backslashes (`\\`) as the separator between folder names. On Unix based operating system such as macOS, Linux, and BSDs, the forward slash (`/`) is used as the path separator. Joining paths can be a headache if your code needs to work on different platforms.\n", 19 | "\n", 20 | "Fortunately, Python provides us with `pathlib.Path.joinpath` to easily handle this." 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "id": "558f6744-f98b-4954-86ce-778ecdab64b7", 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "from pathlib import Path\n", 31 | "\n", 32 | "print(Path('usr').joinpath('bin').joinpath('spam'))\n", 33 | "# usr/bin/spam" 34 | ] 35 | }, 36 | { 37 | "cell_type": "markdown", 38 | "id": "2db708fc", 39 | "metadata": {}, 40 | "source": [ 41 | "`pathlib` also provides a shortcut to joinpath using the `/` operator:" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "id": "9d85fcaa", 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "from pathlib import Path\n", 52 | "\n", 53 | "print(Path('usr') / 'bin' / 'spam')\n", 54 | "# usr/bin/spam" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "id": "792cdc43", 60 | "metadata": {}, 61 | "source": [ 62 | "Joining paths is helpful if you need to create different file paths under the same directory." 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": null, 68 | "id": "8f38e9a5", 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "my_files = ['accounts.txt', 'details.csv', 'invite.docx']\n", 73 | "home = Path.home()\n", 74 | "for filename in my_files:\n", 75 | " print(home / filename)\n", 76 | "\n", 77 | "# /home/docs/accounts.txt\n", 78 | "# /home/docs/details.csv\n", 79 | "# /home/docs/invite.docx" 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "id": "2a7a75e0", 85 | "metadata": {}, 86 | "source": [ 87 | "## The current working directory" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": null, 93 | "id": "c2c19a36-8205-4441-b714-d3e346c7feaf", 94 | "metadata": {}, 95 | "outputs": [], 96 | "source": [ 97 | "from pathlib import Path\n", 98 | "from os import chdir" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "id": "af36de88-300c-44e0-9fc0-5d5ed51ffac0", 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "print(Path.cwd())\n", 109 | "# /home/docs" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "id": "1fdffe11-d64a-470b-ae45-89180663384c", 116 | "metadata": {}, 117 | "outputs": [], 118 | "source": [ 119 | "chdir('/usr/lib/python3.10')\n", 120 | "print(Path.cwd())\n", 121 | "# /usr/lib/python3.10" 122 | ] 123 | }, 124 | { 125 | "cell_type": "markdown", 126 | "id": "0e1ce9b5", 127 | "metadata": {}, 128 | "source": [ 129 | "## Creating new folders" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": null, 135 | "id": "97fb5c45", 136 | "metadata": {}, 137 | "outputs": [], 138 | "source": [ 139 | "from pathlib import Path\n", 140 | "cwd = Path.cwd()\n", 141 | "(cwd / 'delicious' / 'walnut' / 'waffles').mkdir()\n", 142 | "# Traceback (most recent call last):\n", 143 | "# File \"\", line 1, in \n", 144 | "# File \"/usr/lib/python3.10/pathlib.py\", line 1226, in mkdir\n", 145 | "# self._accessor.mkdir(self, mode)\n", 146 | "# File \"/usr/lib/python3.10/pathlib.py\", line 387, in wrapped\n", 147 | "# return strfunc(str(pathobj), *args)\n", 148 | "# FileNotFoundError: [Errno 2] No such file or directory: '/home/docs/delicious/walnut/waffles'" 149 | ] 150 | }, 151 | { 152 | "cell_type": "markdown", 153 | "id": "8bd5ea58", 154 | "metadata": {}, 155 | "source": [ 156 | "The reason of this error is that the ‘delicious’ directory does not exist, so we cannot make the ‘walnut’ and the ‘waffles’ directories under it. To fix this, do:" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "id": "b7a8184a", 163 | "metadata": {}, 164 | "outputs": [], 165 | "source": [ 166 | "from pathlib import Path\n", 167 | "cwd = Path.cwd()\n", 168 | "(cwd / 'delicious' / 'walnut' / 'waffles').mkdir(parents=True)" 169 | ] 170 | }, 171 | { 172 | "cell_type": "markdown", 173 | "id": "b7319db3", 174 | "metadata": {}, 175 | "source": [ 176 | "## Absolute vs. Relative paths\n", 177 | "\n", 178 | "There are two ways to specify a file path.\n", 179 | "\n", 180 | "- An **absolute path**, which always begins with the root folder\n", 181 | "- A **relative path**, which is relative to the program’s current working directory\n", 182 | "\n", 183 | "There are also the dot (`.`) and dot-dot (`..`) folders. These are not real folders, but special names that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this directory.” Two periods (“dot-dot”) means “the parent folder.”\n", 184 | "\n", 185 | "### Handling Absolute paths\n", 186 | "\n", 187 | "To see if a path is an absolute path:" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": null, 193 | "id": "2e9d046c-b1e5-44e5-ac67-9483b3493ee3", 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [ 197 | "from pathlib import Path" 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": null, 203 | "id": "40521631-04ac-49d4-bc39-ad86d4fb00b2", 204 | "metadata": {}, 205 | "outputs": [], 206 | "source": [ 207 | "Path('/').is_absolute()\n", 208 | "# True" 209 | ] 210 | }, 211 | { 212 | "cell_type": "code", 213 | "execution_count": null, 214 | "id": "433eea61-9ee7-471f-8948-5fd0d28bcbdb", 215 | "metadata": {}, 216 | "outputs": [], 217 | "source": [ 218 | "Path('..').is_absolute()\n", 219 | "# False" 220 | ] 221 | }, 222 | { 223 | "cell_type": "markdown", 224 | "id": "ae5bf1ff", 225 | "metadata": {}, 226 | "source": [ 227 | "You can also extract an absolute path:" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": null, 233 | "id": "846267cd-fc86-48c9-87f4-d39b386c5b08", 234 | "metadata": {}, 235 | "outputs": [], 236 | "source": [ 237 | "from pathlib import Path" 238 | ] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": null, 243 | "id": "a7c2286f-4c9b-4edc-a3b2-a877f1956aa4", 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [ 247 | "print(Path.cwd())\n", 248 | "# /home/docs" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": null, 254 | "id": "45d2d8bf-9d91-453e-86df-80d4042f91e6", 255 | "metadata": {}, 256 | "outputs": [], 257 | "source": [ 258 | "print(Path('..').resolve())\n", 259 | "# /home" 260 | ] 261 | }, 262 | { 263 | "cell_type": "markdown", 264 | "id": "7db3d00c", 265 | "metadata": {}, 266 | "source": [ 267 | "### Handling Relative paths\n", 268 | "\n", 269 | "You can get a relative path from a starting path to another path." 270 | ] 271 | }, 272 | { 273 | "cell_type": "code", 274 | "execution_count": null, 275 | "id": "92445191", 276 | "metadata": {}, 277 | "outputs": [], 278 | "source": [ 279 | "from pathlib import Path\n", 280 | "print(Path('/etc/passwd').relative_to('/'))\n", 281 | "# etc/passwd" 282 | ] 283 | }, 284 | { 285 | "cell_type": "markdown", 286 | "id": "4c692dc7", 287 | "metadata": {}, 288 | "source": [ 289 | "## Path and File validity\n", 290 | "\n", 291 | "### Checking if a file/directory exists" 292 | ] 293 | }, 294 | { 295 | "cell_type": "code", 296 | "execution_count": null, 297 | "id": "9f7c2ffa-3755-4a15-9d45-f65f32c91f8a", 298 | "metadata": {}, 299 | "outputs": [], 300 | "source": [ 301 | "from pathlib import Path" 302 | ] 303 | }, 304 | { 305 | "cell_type": "code", 306 | "execution_count": null, 307 | "id": "44d0ba5b-6cc9-452e-b564-228c96ef220f", 308 | "metadata": {}, 309 | "outputs": [], 310 | "source": [ 311 | "Path('.').exists()\n", 312 | "# True" 313 | ] 314 | }, 315 | { 316 | "cell_type": "code", 317 | "execution_count": null, 318 | "id": "cc4cd800-dd0d-467e-9db8-ca13b00d3e5d", 319 | "metadata": {}, 320 | "outputs": [], 321 | "source": [ 322 | "Path('setup.py').exists()\n", 323 | "# True" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": null, 329 | "id": "13509382-36e0-4569-8977-5ab71e40e56d", 330 | "metadata": {}, 331 | "outputs": [], 332 | "source": [ 333 | "Path('/etc').exists()\n", 334 | "# True" 335 | ] 336 | }, 337 | { 338 | "cell_type": "code", 339 | "execution_count": null, 340 | "id": "9a609364-2957-489e-99e3-b1b0822a384f", 341 | "metadata": {}, 342 | "outputs": [], 343 | "source": [ 344 | "Path('nonexistentfile').exists()\n", 345 | "# False" 346 | ] 347 | }, 348 | { 349 | "cell_type": "markdown", 350 | "id": "9ef4b318", 351 | "metadata": {}, 352 | "source": [ 353 | "### Checking if a path is a file" 354 | ] 355 | }, 356 | { 357 | "cell_type": "code", 358 | "execution_count": null, 359 | "id": "d44642e6-39ee-4ac3-8da3-af6817da7265", 360 | "metadata": {}, 361 | "outputs": [], 362 | "source": [ 363 | "from pathlib import Path" 364 | ] 365 | }, 366 | { 367 | "cell_type": "code", 368 | "execution_count": null, 369 | "id": "45bd0a7e-2cc0-4170-85f5-42d7f1bbdf5a", 370 | "metadata": {}, 371 | "outputs": [], 372 | "source": [ 373 | "Path('setup.py').is_file()\n", 374 | "# True" 375 | ] 376 | }, 377 | { 378 | "cell_type": "code", 379 | "execution_count": null, 380 | "id": "b6a73928-30fb-4eaf-97e8-1a13cab7bd12", 381 | "metadata": {}, 382 | "outputs": [], 383 | "source": [ 384 | "Path('/home').is_file()\n", 385 | "# False" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": null, 391 | "id": "4bb61baf-ff76-4523-8ffa-f78f397cf7c5", 392 | "metadata": {}, 393 | "outputs": [], 394 | "source": [ 395 | "Path('nonexistentfile').is_file()\n", 396 | "# False" 397 | ] 398 | }, 399 | { 400 | "cell_type": "markdown", 401 | "id": "df5dbcb2", 402 | "metadata": {}, 403 | "source": [ 404 | "### Checking if a path is a directory" 405 | ] 406 | }, 407 | { 408 | "cell_type": "code", 409 | "execution_count": null, 410 | "id": "4f77ef73-0bd3-4e28-9ff6-244e6d6c69de", 411 | "metadata": {}, 412 | "outputs": [], 413 | "source": [ 414 | "from pathlib import Path" 415 | ] 416 | }, 417 | { 418 | "cell_type": "code", 419 | "execution_count": null, 420 | "id": "77861a9b-d9ee-4071-aac0-b8db6e4e21f3", 421 | "metadata": {}, 422 | "outputs": [], 423 | "source": [ 424 | "Path('/').is_dir()\n", 425 | "# True" 426 | ] 427 | }, 428 | { 429 | "cell_type": "code", 430 | "execution_count": null, 431 | "id": "7abec6a8-9d1e-426e-a16b-cb671880bfd1", 432 | "metadata": {}, 433 | "outputs": [], 434 | "source": [ 435 | "Path('setup.py').is_dir()\n", 436 | "# False" 437 | ] 438 | }, 439 | { 440 | "cell_type": "code", 441 | "execution_count": null, 442 | "id": "d0ee82e2-b60a-4349-a240-37431eaa9fc6", 443 | "metadata": {}, 444 | "outputs": [], 445 | "source": [ 446 | "Path('/spam').is_dir()\n", 447 | "# False" 448 | ] 449 | }, 450 | { 451 | "cell_type": "markdown", 452 | "id": "ef3ca005", 453 | "metadata": {}, 454 | "source": [ 455 | "## Getting a file’s size in bytes" 456 | ] 457 | }, 458 | { 459 | "cell_type": "code", 460 | "execution_count": null, 461 | "id": "d367e974", 462 | "metadata": {}, 463 | "outputs": [], 464 | "source": [ 465 | "from pathlib import Path\n", 466 | "\n", 467 | "stat = Path('/bin/python3.10').stat()\n", 468 | "print(stat) # stat contains some other information about the file as well\n", 469 | "# os.stat_result(st_mode=33261, st_ino=141087, st_dev=2051, st_nlink=2, st_uid=0,\n", 470 | "# --snip--\n", 471 | "# st_gid=0, st_size=10024, st_atime=1517725562, st_mtime=1515119809, st_ctime=1517261276)\n", 472 | "\n", 473 | "print(stat.st_size) # size in bytes\n", 474 | "# 10024" 475 | ] 476 | }, 477 | { 478 | "cell_type": "markdown", 479 | "id": "9af71c35", 480 | "metadata": {}, 481 | "source": [ 482 | "## Listing directories" 483 | ] 484 | }, 485 | { 486 | "cell_type": "code", 487 | "execution_count": null, 488 | "id": "70fead1e", 489 | "metadata": {}, 490 | "outputs": [], 491 | "source": [ 492 | "from pathlib import Path\n", 493 | "\n", 494 | "for f in Path('/usr/bin').iterdir():\n", 495 | " print(f)\n", 496 | "\n", 497 | "# ...\n", 498 | "# /usr/bin/tiff2rgba\n", 499 | "# /usr/bin/iconv\n", 500 | "# /usr/bin/ldd\n", 501 | "# /usr/bin/cache_restore\n", 502 | "# /usr/bin/udiskie\n", 503 | "# /usr/bin/unix2dos\n", 504 | "# /usr/bin/t1reencode\n", 505 | "# /usr/bin/epstopdf\n", 506 | "# /usr/bin/idle3\n", 507 | "# ..." 508 | ] 509 | }, 510 | { 511 | "cell_type": "markdown", 512 | "id": "8c8720f2", 513 | "metadata": {}, 514 | "source": [ 515 | "## Directory file sizes\n", 516 | "\n", 517 | "\n", 518 | "\n", 519 | "WARNING\n", 520 | "\n", 521 | "Directories themselves also have a size! So, you might want to check for whether a path is a file or directory using the methods in the methods discussed in the above section." 522 | ] 523 | }, 524 | { 525 | "cell_type": "code", 526 | "execution_count": null, 527 | "id": "5e7d4219", 528 | "metadata": {}, 529 | "outputs": [], 530 | "source": [ 531 | "from pathlib import Path\n", 532 | "\n", 533 | "total_size = 0\n", 534 | "\n", 535 | "for sub_path in Path('/usr/bin').iterdir():\n", 536 | " total_size += sub_path.stat().st_size\n", 537 | "\n", 538 | "print(total_size)\n", 539 | "# 1903178911" 540 | ] 541 | }, 542 | { 543 | "cell_type": "markdown", 544 | "id": "ccdc98b7", 545 | "metadata": {}, 546 | "source": [ 547 | "## Deleting files and folders\n", 548 | "\n", 549 | "- Calling `Path.unlink()` will delete the file at path.\n", 550 | "- Calling `Path.rmdir()` will delete the folder at path. This folder must be empty of any files or folders." 551 | ] 552 | } 553 | ], 554 | "metadata": { 555 | "kernelspec": { 556 | "display_name": "Python 3 (ipykernel)", 557 | "language": "python", 558 | "name": "python3" 559 | }, 560 | "language_info": { 561 | "codemirror_mode": { 562 | "name": "ipython", 563 | "version": 3 564 | }, 565 | "file_extension": ".py", 566 | "mimetype": "text/x-python", 567 | "name": "python", 568 | "nbconvert_exporter": "python", 569 | "pygments_lexer": "ipython3", 570 | "version": "3.12.0" 571 | } 572 | }, 573 | "nbformat": 4, 574 | "nbformat_minor": 5 575 | } 576 | -------------------------------------------------------------------------------- /standard.library.07.Random.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "7cabcc95", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Random Module\n", 9 | "\n", 10 | "The [random](https://docs.python.org/3/library/random.html) module is a built-in module that allow us to generate random elements." 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "id": "f06df511", 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "import random" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "id": "9c5a82ce", 26 | "metadata": {}, 27 | "source": [ 28 | "## seed()\n", 29 | "\n", 30 | "The `seed` method is used to initialize the random number generator." 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "id": "f4a0c7c9", 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "random.seed(1)\n", 41 | "random.random()\n", 42 | "# 0.13436424411240122" 43 | ] 44 | }, 45 | { 46 | "cell_type": "markdown", 47 | "id": "a09e6f6b", 48 | "metadata": {}, 49 | "source": [ 50 | "Setting the seed to a number will always return the same random number:" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "id": "3df0fdd7-977b-4f05-8b68-d6d0a2a5f056", 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "random.seed(1)\n", 61 | "random.random()\n", 62 | "# 0.13436424411240122" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": null, 68 | "id": "b776c2cd-854e-48b7-99ba-5341b73fa12f", 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "random.seed(1)\n", 73 | "random.random()\n", 74 | "# 0.13436424411240122" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": null, 80 | "id": "b13a9888-a785-4427-bebb-25bfe89e32d8", 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "random.seed(1)\n", 85 | "random.random()\n", 86 | "# 0.13436424411240122" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "id": "2d65f20e-bfdd-4487-9d03-dbe5d5298967", 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "random.seed(1)\n", 97 | "random.random()\n", 98 | "# 0.13436424411240122" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": null, 104 | "id": "86240f28-bd2f-405d-b724-c54a77e8763c", 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "random.seed(1)\n", 109 | "random.random()\n", 110 | "# 0.13436424411240122" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "id": "e8f0b46a", 116 | "metadata": {}, 117 | "source": [ 118 | "The default value of the `seed` method is the *current system time*, that is why we always get a different number:" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": null, 124 | "id": "b1a5d386-0596-4881-b7a0-a978e9772bb1", 125 | "metadata": {}, 126 | "outputs": [], 127 | "source": [ 128 | "random.random()\n", 129 | "# 0.8474337369372327" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": null, 135 | "id": "c6201276-6949-4be5-8670-9005c8df00c6", 136 | "metadata": {}, 137 | "outputs": [], 138 | "source": [ 139 | "random.random()\n", 140 | "# 0.763774618976614" 141 | ] 142 | }, 143 | { 144 | "cell_type": "code", 145 | "execution_count": null, 146 | "id": "6368213b-451f-429e-a5de-0d22d0ed344d", 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "random.random()\n", 151 | "# 0.2550690257394217" 152 | ] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "id": "591a336c", 157 | "metadata": {}, 158 | "source": [ 159 | "## randint()" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": null, 165 | "id": "d17d0c1d", 166 | "metadata": {}, 167 | "outputs": [], 168 | "source": [ 169 | "random.randint(start: int, stop: int)" 170 | ] 171 | }, 172 | { 173 | "cell_type": "markdown", 174 | "id": "d8580495", 175 | "metadata": {}, 176 | "source": [ 177 | "This method returns a random number between a given start and stop parameters:" 178 | ] 179 | }, 180 | { 181 | "cell_type": "code", 182 | "execution_count": null, 183 | "id": "79237b56-e5e0-485e-b8e6-f46bfaa9205a", 184 | "metadata": {}, 185 | "outputs": [], 186 | "source": [ 187 | "random.randint(1, 5)\n", 188 | "# 3" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "id": "26bac9f3-674d-4eb2-b16e-0beae35a7772", 195 | "metadata": {}, 196 | "outputs": [], 197 | "source": [ 198 | "random.randint(1, 5)\n", 199 | "# 2" 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": null, 205 | "id": "43447299-ab04-4da5-9891-e66d3a09a86a", 206 | "metadata": {}, 207 | "outputs": [], 208 | "source": [ 209 | "random.randint(1, 5)\n", 210 | "# 5" 211 | ] 212 | }, 213 | { 214 | "cell_type": "code", 215 | "execution_count": null, 216 | "id": "4b479af1-0601-4930-86a8-5ff51beb0ba0", 217 | "metadata": {}, 218 | "outputs": [], 219 | "source": [ 220 | "random.randint(1, 5)\n", 221 | "# 1" 222 | ] 223 | }, 224 | { 225 | "cell_type": "code", 226 | "execution_count": null, 227 | "id": "489f6ef4-1841-46ad-a548-eeb6b4079671", 228 | "metadata": {}, 229 | "outputs": [], 230 | "source": [ 231 | "random.randint(1, 5)\n", 232 | "# 3" 233 | ] 234 | }, 235 | { 236 | "cell_type": "code", 237 | "execution_count": null, 238 | "id": "d9deb907-d8e0-494b-94c0-8c5e414e8ec0", 239 | "metadata": {}, 240 | "outputs": [], 241 | "source": [ 242 | "random.randint(1, 5)\n", 243 | "# 1" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "id": "c29f6173", 249 | "metadata": {}, 250 | "source": [ 251 | "## choice()\n", 252 | "\n", 253 | "The `choice` method return a randomly selected element from an iterable, like a `list`, `set` or `str`:" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": null, 259 | "id": "aa1eca20-4f3c-474d-86f4-991a314e9eb8", 260 | "metadata": {}, 261 | "outputs": [], 262 | "source": [ 263 | "random.choice([1, 2, 3, 4])\n", 264 | "# 1" 265 | ] 266 | }, 267 | { 268 | "cell_type": "code", 269 | "execution_count": null, 270 | "id": "a60bad80-fe9e-4a40-b9f4-8b682e531267", 271 | "metadata": {}, 272 | "outputs": [], 273 | "source": [ 274 | "random.choice([1, 2, 3, 4])\n", 275 | "# 2" 276 | ] 277 | }, 278 | { 279 | "cell_type": "code", 280 | "execution_count": null, 281 | "id": "2443f3b9-3a4f-4d2b-a319-763dbc0dd062", 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [ 285 | "random.choice([1, 2, 3, 4])\n", 286 | "# 4" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": null, 292 | "id": "c90901a5-753a-407c-a277-8aa8f72582da", 293 | "metadata": {}, 294 | "outputs": [], 295 | "source": [ 296 | "random.choice([1, 2, 3, 4])\n", 297 | "# 4" 298 | ] 299 | }, 300 | { 301 | "cell_type": "markdown", 302 | "id": "d312abfd", 303 | "metadata": {}, 304 | "source": [ 305 | "## shuffle()\n", 306 | "\n", 307 | "The `shuffle` method takes in an iterable and shuffle it:" 308 | ] 309 | }, 310 | { 311 | "cell_type": "code", 312 | "execution_count": null, 313 | "id": "4e9bbbe8-2152-4b2c-a762-0d91edcdddd1", 314 | "metadata": {}, 315 | "outputs": [], 316 | "source": [ 317 | "my_list = [1, 2, 3, 4]" 318 | ] 319 | }, 320 | { 321 | "cell_type": "code", 322 | "execution_count": null, 323 | "id": "f91ecdd8-1455-4eb0-81e5-95f176c4e0a0", 324 | "metadata": {}, 325 | "outputs": [], 326 | "source": [ 327 | "random.shuffle(my_list)\n", 328 | "my_list\n", 329 | "# [1, 4, 3, 2]" 330 | ] 331 | }, 332 | { 333 | "cell_type": "code", 334 | "execution_count": null, 335 | "id": "19c804a1-54ea-4f54-bbdc-4e6def62055d", 336 | "metadata": {}, 337 | "outputs": [], 338 | "source": [ 339 | "random.shuffle(my_list)\n", 340 | "my_list\n", 341 | "# [2, 4, 3, 1]" 342 | ] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": null, 347 | "id": "0cad5eaa-5c4d-42d1-ba26-71063fb7cfc7", 348 | "metadata": {}, 349 | "outputs": [], 350 | "source": [ 351 | "random.shuffle(my_list)\n", 352 | "my_list\n", 353 | "# [4, 2, 3, 1]" 354 | ] 355 | }, 356 | { 357 | "cell_type": "markdown", 358 | "id": "4266592a", 359 | "metadata": {}, 360 | "source": [ 361 | "## sample()" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": null, 367 | "id": "7b6363ae", 368 | "metadata": {}, 369 | "outputs": [], 370 | "source": [ 371 | "random.sample(iterable, k: int)" 372 | ] 373 | }, 374 | { 375 | "cell_type": "markdown", 376 | "id": "a6d35158", 377 | "metadata": {}, 378 | "source": [ 379 | "`sample` returns a list with a random selection from an iterable. The number of elements returned is equal to the `k` parameter:" 380 | ] 381 | }, 382 | { 383 | "cell_type": "code", 384 | "execution_count": null, 385 | "id": "993b143c-dc9d-4229-8795-42437f2b961f", 386 | "metadata": {}, 387 | "outputs": [], 388 | "source": [ 389 | "random.sample([1, 2, 3, 4], 1)\n", 390 | "# [3]" 391 | ] 392 | }, 393 | { 394 | "cell_type": "code", 395 | "execution_count": null, 396 | "id": "f9320c40-7c47-49c5-a3b9-a370d4cf1276", 397 | "metadata": {}, 398 | "outputs": [], 399 | "source": [ 400 | "random.sample([1, 2, 3, 4], 2)\n", 401 | "# [3, 4]" 402 | ] 403 | }, 404 | { 405 | "cell_type": "code", 406 | "execution_count": null, 407 | "id": "8d1ad05a-c53f-4b82-9834-59b6952e953f", 408 | "metadata": {}, 409 | "outputs": [], 410 | "source": [ 411 | "random.sample([1, 2, 3, 4], 3)\n", 412 | "# [4, 3, 2]" 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "execution_count": null, 418 | "id": "3a38f4f7-6ded-4c7f-9c6a-a7309efbcdb5", 419 | "metadata": {}, 420 | "outputs": [], 421 | "source": [ 422 | "random.sample([1, 2, 3, 4], 4)\n", 423 | "# [1, 2, 4, 3]" 424 | ] 425 | }, 426 | { 427 | "cell_type": "markdown", 428 | "id": "ea1c199f", 429 | "metadata": {}, 430 | "source": [ 431 | "## random()\n", 432 | "\n", 433 | "The `random` method returns a random floating point number between 0.0 and 1.0:" 434 | ] 435 | }, 436 | { 437 | "cell_type": "code", 438 | "execution_count": null, 439 | "id": "7e9a5841-ef72-4271-a49d-8ebc75af8cf0", 440 | "metadata": {}, 441 | "outputs": [], 442 | "source": [ 443 | "random.random()\n", 444 | "# 0.4143139993007743" 445 | ] 446 | }, 447 | { 448 | "cell_type": "code", 449 | "execution_count": null, 450 | "id": "9fde1001-a9e3-42f8-b541-cf98f35b0c64", 451 | "metadata": {}, 452 | "outputs": [], 453 | "source": [ 454 | "random.random()\n", 455 | "# 0.17300740157905092" 456 | ] 457 | }, 458 | { 459 | "cell_type": "code", 460 | "execution_count": null, 461 | "id": "a2b0391e-7d1a-4bc1-a5e5-9299200c854d", 462 | "metadata": {}, 463 | "outputs": [], 464 | "source": [ 465 | "random.random()\n", 466 | "# 0.548798761388153" 467 | ] 468 | }, 469 | { 470 | "cell_type": "code", 471 | "execution_count": null, 472 | "id": "c2963e05-59c6-43d3-b61f-81009f13631e", 473 | "metadata": {}, 474 | "outputs": [], 475 | "source": [ 476 | "random.random()\n", 477 | "# 0.7030407620656315" 478 | ] 479 | }, 480 | { 481 | "cell_type": "markdown", 482 | "id": "08965f4e", 483 | "metadata": {}, 484 | "source": [ 485 | "## uniform()\n", 486 | "\n", 487 | "the `uniform` method is similar to `randint`, but return a floating point number:" 488 | ] 489 | }, 490 | { 491 | "cell_type": "code", 492 | "execution_count": null, 493 | "id": "66a4a885-2778-4aa0-8e19-65fd33d524b1", 494 | "metadata": {}, 495 | "outputs": [], 496 | "source": [ 497 | "random.uniform(1, 5)\n", 498 | "# 3.697943322009309" 499 | ] 500 | }, 501 | { 502 | "cell_type": "code", 503 | "execution_count": null, 504 | "id": "a78cf05e-3aaf-48e8-8200-4be4ecd6f65c", 505 | "metadata": {}, 506 | "outputs": [], 507 | "source": [ 508 | "random.uniform(1, 5)\n", 509 | "# 2.498812082006561" 510 | ] 511 | }, 512 | { 513 | "cell_type": "code", 514 | "execution_count": null, 515 | "id": "ad0a4325-27f0-4154-940e-c2747adfc2dc", 516 | "metadata": {}, 517 | "outputs": [], 518 | "source": [ 519 | "random.uniform(1, 5)\n", 520 | "# 2.7558465201782525" 521 | ] 522 | }, 523 | { 524 | "cell_type": "code", 525 | "execution_count": null, 526 | "id": "fba0b2ac-e5a4-4463-8e85-d3bf712d1757", 527 | "metadata": {}, 528 | "outputs": [], 529 | "source": [ 530 | "random.uniform(1, 5)\n", 531 | "# 3.0337059529999273" 532 | ] 533 | } 534 | ], 535 | "metadata": { 536 | "kernelspec": { 537 | "display_name": "Python 3 (ipykernel)", 538 | "language": "python", 539 | "name": "python3" 540 | }, 541 | "language_info": { 542 | "codemirror_mode": { 543 | "name": "ipython", 544 | "version": 3 545 | }, 546 | "file_extension": ".py", 547 | "mimetype": "text/x-python", 548 | "name": "python", 549 | "nbconvert_exporter": "python", 550 | "pygments_lexer": "ipython3", 551 | "version": "3.12.0" 552 | } 553 | }, 554 | "nbformat": 4, 555 | "nbformat_minor": 5 556 | } 557 | -------------------------------------------------------------------------------- /standard.library.08.Shelve.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "d68ed15e", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Shelve Module\n", 9 | "\n", 10 | "From the [Python 3 documentation](https://docs.python.org/3/library/shelve.html)\n", 11 | "\n", 12 | "A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.\n", 13 | "\n", 14 | "## Save variables" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "id": "5364ecd1", 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "import shelve\n", 25 | "\n", 26 | "wife = ['Pretty', 'Lovely', 'Nice']\n", 27 | "with shelve.open('mydata') as shelf_file:\n", 28 | " shelf_file['wife'] = wife" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "id": "488b798d", 34 | "metadata": {}, 35 | "source": [ 36 | "## Open and read variables" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "id": "9202f807", 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "with shelve.open('mydata') as shelf_file:\n", 47 | " print(type(shelf_file))\n", 48 | " print(shelf_file['wife'])\n", 49 | "\n", 50 | "# \n", 51 | "# ['Pretty', 'Lovely', 'Nice']" 52 | ] 53 | }, 54 | { 55 | "cell_type": "markdown", 56 | "id": "38a29ec4", 57 | "metadata": {}, 58 | "source": [ 59 | "Just like dictionaries, `shelf` values have `keys()` and `values()` methods that will return list-like values of the keys and values in the shelf. Since these methods return list-like values instead of true lists, you should pass them to the `list()` function to get them in list form." 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": null, 65 | "id": "ec2f8d6b-533b-4d0f-8a87-5d7466648d73", 66 | "metadata": {}, 67 | "outputs": [], 68 | "source": [ 69 | "with shelve.open('mydata') as shelf_file:\n", 70 | " print(list(shelf_file.keys()))\n", 71 | " print(list(shelf_file.values()))\n", 72 | "\n", 73 | "# ['wife']\n", 74 | "# [['Pretty', 'Lovely', 'Nice']]" 75 | ] 76 | } 77 | ], 78 | "metadata": { 79 | "kernelspec": { 80 | "display_name": "Python 3 (ipykernel)", 81 | "language": "python", 82 | "name": "python3" 83 | }, 84 | "language_info": { 85 | "codemirror_mode": { 86 | "name": "ipython", 87 | "version": 3 88 | }, 89 | "file_extension": ".py", 90 | "mimetype": "text/x-python", 91 | "name": "python", 92 | "nbconvert_exporter": "python", 93 | "pygments_lexer": "ipython3", 94 | "version": "3.12.0" 95 | } 96 | }, 97 | "nbformat": 4, 98 | "nbformat_minor": 5 99 | } 100 | -------------------------------------------------------------------------------- /standard.library.09.Zipfile.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "9dbafb31", 6 | "metadata": {}, 7 | "source": [ 8 | "# Python Zipfile Module\n", 9 | "\n", 10 | "From the [Python 3 documentation](https://docs.python.org/3/library/zipfile.html)\n", 11 | "\n", 12 | "This module provides tools to create, read, write, append, and list a ZIP file.\n", 13 | "\n", 14 | "## Reading ZIP files" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": null, 20 | "id": "d3cdbd95", 21 | "metadata": {}, 22 | "outputs": [], 23 | "source": [ 24 | "with zipfile.ZipFile('example.zip') as example_zip:\n", 25 | " print(example_zip.namelist())\n", 26 | " spam_info = example_zip.getinfo('spam.txt')\n", 27 | " print(spam_info.file_size)\n", 28 | " print(spam_info.compress_size)\n", 29 | " print('Compressed file is %sx smaller!' % (round(spam_info.file_size / spam_info.compress_size, 2)))\n", 30 | "\n", 31 | "# ['spam.txt', 'cats/', 'cats/catnames.txt', 'cats/zophie.jpg']\n", 32 | "# 13908\n", 33 | "# 3828\n", 34 | "# 'Compressed file is 3.63x smaller!'" 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "id": "119bc06d", 40 | "metadata": {}, 41 | "source": [ 42 | "## Extracting from ZIP Files\n", 43 | "\n", 44 | "The `extractall()` method for ZipFile objects extracts all the files and folders from a ZIP file into the current working directory." 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": null, 50 | "id": "7e23b7c2", 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "with zipfile.ZipFile('example.zip') as example_zip:\n", 55 | " example_zip.extractall()" 56 | ] 57 | }, 58 | { 59 | "cell_type": "markdown", 60 | "id": "62d06233", 61 | "metadata": {}, 62 | "source": [ 63 | "The `extract()` method for ZipFile objects will extract a single file from the ZIP file:" 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "id": "3af8718b", 70 | "metadata": {}, 71 | "outputs": [], 72 | "source": [ 73 | "with zipfile.ZipFile('example.zip') as example_zip:\n", 74 | " print(example_zip.extract('spam.txt'))\n", 75 | " print(example_zip.extract('spam.txt', 'C:\\\\some\\\\new\\\\folders'))\n", 76 | "\n", 77 | "# 'C:\\\\spam.txt'\n", 78 | "# 'C:\\\\some\\\\new\\\\folders\\\\spam.txt'" 79 | ] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "id": "3afa11be", 84 | "metadata": {}, 85 | "source": [ 86 | "## Creating and Adding to ZIP Files" 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": null, 92 | "id": "c96edcf9", 93 | "metadata": {}, 94 | "outputs": [], 95 | "source": [ 96 | "import zipfile\n", 97 | "\n", 98 | "with zipfile.ZipFile('new.zip', 'w') as new_zip:\n", 99 | " new_zip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)" 100 | ] 101 | }, 102 | { 103 | "cell_type": "markdown", 104 | "id": "3867d96d", 105 | "metadata": {}, 106 | "source": [ 107 | "This code will create a new ZIP file named new.zip that has the compressed contents of spam.txt.\n", 108 | "\n", 109 | "## Reading metadata of ZIP files\n", 110 | "\n", 111 | "### Getting the filenames with namelist()" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "id": "9bf7c772", 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "import zipfile\n", 122 | "\n", 123 | "with zipfile.ZipFile('example.zip', 'r') as zf:\n", 124 | " print(zf.namelist())\n", 125 | "\n", 126 | "# ['README.txt']" 127 | ] 128 | }, 129 | { 130 | "cell_type": "markdown", 131 | "id": "81a5d435", 132 | "metadata": {}, 133 | "source": [ 134 | "### Getting all metadata with infolist()" 135 | ] 136 | }, 137 | { 138 | "cell_type": "code", 139 | "execution_count": null, 140 | "id": "5a63ede2-31e9-4fb9-b774-2283d9153479", 141 | "metadata": {}, 142 | "outputs": [], 143 | "source": [ 144 | "import datetime\n", 145 | "import zipfile\n", 146 | "\n", 147 | "with zipfile.ZipFile(archive_name) as zf:\n", 148 | " for info in zf.infolist():\n", 149 | " system = 'Windows' if info.create_system == 0 else 'Unix'\n", 150 | " modified = datetime.datetime(*info.date_time)\n", 151 | " print(info.filename)\n", 152 | " print(f'Comment : {info.comment}')\n", 153 | " print(f'Modified : {modified}')\n", 154 | " print(f'System : {system}')\n", 155 | " print(f'ZIP version : {info.create_version}')\n", 156 | " print(f'Compressed : {info.compress_size} bytes')\n", 157 | " print(f'Uncompressed: {info.file_size} bytes')\n", 158 | "\n", 159 | "# README.txt\n", 160 | "# Comment : b''\n", 161 | "# Modified : 2022-11-15 06:48:02\n", 162 | "# System : Unix\n", 163 | "# ZIP version : 30\n", 164 | "# Compressed : 65 bytes\n", 165 | "# Uncompressed: 76 bytes" 166 | ] 167 | } 168 | ], 169 | "metadata": { 170 | "kernelspec": { 171 | "display_name": "Python 3 (ipykernel)", 172 | "language": "python", 173 | "name": "python3" 174 | }, 175 | "language_info": { 176 | "codemirror_mode": { 177 | "name": "ipython", 178 | "version": 3 179 | }, 180 | "file_extension": ".py", 181 | "mimetype": "text/x-python", 182 | "name": "python", 183 | "nbconvert_exporter": "python", 184 | "pygments_lexer": "ipython3", 185 | "version": "3.12.0" 186 | } 187 | }, 188 | "nbformat": 4, 189 | "nbformat_minor": 5 190 | } 191 | --------------------------------------------------------------------------------