├── .devcontainer ├── Dockerfile ├── devcontainer.json └── startup.sh ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ └── main.yml ├── .gitignore ├── .vscode └── settings.json ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── examples ├── 01_01_functions │ ├── functions_begin.py │ └── functions_end.py ├── 01_02_code_reuse │ ├── code_reuse_begin.py │ └── code_reuse_end.py ├── 01_03_parameters_arguments │ ├── parameters_arguments_begin.py │ └── parameters_arguments_end.py ├── 01_04_multiple_parameters │ ├── multiple_parameters_begin.py │ └── multiple_parameters_end.py ├── 01_05_local_global_variables │ ├── local_global_variables_begin.py │ └── local_global_variables_end.py ├── 02_01_objects │ └── objects_commands.py ├── 02_02_classes │ ├── classes_begin.py │ └── classes_end.py ├── 02_03_object_names │ ├── object_names_begin.py │ └── object_names_end.py ├── 02_04_mutability │ └── mutability_commands.py ├── 03_01_inheritance │ ├── inheritance_begin.py │ └── inheritance_end.py ├── 03_02_overriding │ ├── overriding_begin.py │ └── overriding_end.py ├── 04_01_modules │ └── modules_commands.py ├── 04_02_packages │ └── packages_commands.py ├── 05_01_lists │ └── lists_commands.py ├── 05_02_multidimensional_lists │ ├── multidimensional_lists_begin.py │ └── multidimensional_lists_commands.py ├── 05_03_tuples │ └── tuples_commands.py ├── 06_01_queues │ └── queues_commands.py ├── 06_02_stacks │ └── stacks_commands.py ├── 07_01_create_combine_sets │ ├── create_combine_sets_begin.py │ └── create_combine_sets_end.py ├── 07_02_sort_sets │ ├── sort_sets_begin.py │ └── sort_sets_end.py ├── 07_03_add_remove_sets │ ├── add_remove_sets_begin.py │ └── add_remove_sets_end.py ├── 08_01_dictionaries │ ├── dictionaries_begin.py │ └── dictionaries_end.py ├── 08_02_add_to_dictionaries │ ├── add_to_dictionaries_begin.py │ └── add_to_dictionaries_end.py ├── 08_03_reverse_lookup │ ├── reverse_lookup_begin.py │ └── reverse_lookup_end.py ├── 09_01_if_else_statements │ ├── if_else_statement_begin.py │ └── if_else_statement_end.py ├── 09_02_match_statements │ ├── match_statements_begin.py │ └── match_statements_end.py ├── 10_01_for_loops │ ├── for_loops_begin.py │ └── for_loops_end.py ├── 10_02_while_loops │ ├── while_loops_begin.py │ └── while_loops_end.py ├── 10_03_for_break │ ├── for_break_begin.py │ └── for_break_end.py ├── 11_01_catch_errors │ ├── catch_errors_begin.py │ └── catch_errors_end.py ├── 11_02_validate_input │ ├── validate_input_begin.py │ └── validate_input_end.py ├── 11_03_custom_errors │ ├── custom_errors_begin.py │ └── custom_errors_end.py ├── 12_01_polling │ ├── front_door.txt │ ├── polling_begin.py │ └── polling_end.py └── 12_02_event_driven │ ├── event_driven_begin.py │ └── event_driven_end.py └── requirements.txt /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # See here for image contents: https://github.com/microsoft/vscode-dev-containers/tree/v0.233.0/containers/python-3/.devcontainer/base.Dockerfile 2 | 3 | # [Choice] Python version (use -bullseye variants on local arm64/Apple Silicon): 3, 3.10, 3.9, 3.8, 3.7, 3.6, 3-bullseye, 3.10-bullseye, 3.9-bullseye, 3.8-bullseye, 3.7-bullseye, 3.6-bullseye, 3-buster, 3.10-buster, 3.9-buster, 3.8-buster, 3.7-buster, 3.6-buster 4 | ARG VARIANT="3.10" 5 | FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} 6 | 7 | # [Choice] Node.js version: none, lts/*, 16, 14, 12, 10 8 | ARG NODE_VERSION="none" 9 | RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask 0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi 10 | 11 | # [Optional] If your pip requirements rarely change, uncomment this section to add them to the image. 12 | # COPY requirements.txt /tmp/pip-tmp/ 13 | # RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \ 14 | # && rm -rf /tmp/pip-tmp 15 | 16 | # [Optional] Uncomment this section to install additional OS packages. 17 | # RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ 18 | # && apt-get -y install --no-install-recommends 19 | 20 | # [Optional] Uncomment this line to install global node packages. 21 | # RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1 22 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Python 3", 3 | "build": { 4 | "dockerfile": "Dockerfile", 5 | "context": "..", 6 | "args": { 7 | "VARIANT": "3.10", // Set Python version here 8 | "NODE_VERSION": "lts/*" 9 | } 10 | }, 11 | "settings": { 12 | "python.defaultInterpreterPath": "/usr/local/bin/python", 13 | "python.linting.enabled": true, 14 | "python.linting.pylintEnabled": true, 15 | "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8", 16 | "python.formatting.blackPath": "/usr/local/py-utils/bin/black", 17 | "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf", 18 | "python.linting.banditPath": "/usr/local/py-utils/bin/bandit", 19 | "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8", 20 | "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy", 21 | "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle", 22 | "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle", 23 | "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint", 24 | "python.linting.pylintArgs": ["--disable=C0111"] 25 | }, 26 | "extensions": [ 27 | "ms-python.python", 28 | "ms-python.vscode-pylance" 29 | ], 30 | "remoteUser": "vscode", 31 | "onCreateCommand": "echo PS1='\"$ \"' >> ~/.bashrc", //Set Terminal Prompt to $ 32 | "postCreateCommand": "sh .devcontainer/startup.sh" 33 | } 34 | -------------------------------------------------------------------------------- /.devcontainer/startup.sh: -------------------------------------------------------------------------------- 1 | if [ -f requirements.txt ]; then 2 | pip install --user -r requirements.txt 3 | fi -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Codeowners for these exercise files: 2 | # * (asterisk) denotes "all files and folders" 3 | # Example: * @producer @instructor 4 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 7 | 8 | ## Issue Overview 9 | 10 | 11 | ## Describe your environment 12 | 13 | 14 | ## Steps to Reproduce 15 | 16 | 1. 17 | 2. 18 | 3. 19 | 4. 20 | 21 | ## Expected Behavior 22 | 23 | 24 | ## Current Behavior 25 | 26 | 27 | ## Possible Solution 28 | 29 | 30 | ## Screenshots / Video 31 | 32 | 33 | ## Related Issues 34 | 35 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Copy To Branches 2 | on: 3 | workflow_dispatch: 4 | jobs: 5 | copy-to-branches: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v2 9 | with: 10 | fetch-depth: 0 11 | - name: Copy To Branches Action 12 | uses: planetoftheweb/copy-to-branches@v1.2 13 | env: 14 | key: main 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | node_modules 3 | .tmp 4 | npm-debug.log 5 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.bracketPairColorization.enabled": true, 3 | "editor.cursorBlinking": "solid", 4 | "editor.fontFamily": "ui-monospace, Menlo, Monaco, 'Cascadia Mono', 'Segoe UI Mono', 'Roboto Mono', 'Oxygen Mono', 'Ubuntu Monospace', 'Source Code Pro', 'Fira Mono', 'Droid Sans Mono', 'Courier New', monospace", 5 | "editor.fontLigatures": false, 6 | "editor.fontSize": 28, 7 | "editor.formatOnPaste": true, 8 | "editor.formatOnSave": true, 9 | "editor.lineNumbers": "on", 10 | "editor.matchBrackets": "always", 11 | "editor.minimap.enabled": false, 12 | "editor.smoothScrolling": true, 13 | "editor.tabSize": 2, 14 | "editor.useTabStops": true, 15 | "emmet.triggerExpansionOnTab": true, 16 | "explorer.openEditors.visible": 0, 17 | "files.autoSave": "afterDelay", 18 | "screencastMode.onlyKeyboardShortcuts": true, 19 | "terminal.integrated.fontSize": 28, 20 | "workbench.activityBar.visible": true, 21 | "workbench.colorTheme": "Visual Studio Dark", 22 | "workbench.fontAliasing": "antialiased", 23 | "workbench.statusBar.visible": true 24 | } 25 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 2 | Contribution Agreement 3 | ====================== 4 | 5 | This repository does not accept pull requests (PRs). All pull requests will be closed. 6 | 7 | However, if any contributions (through pull requests, issues, feedback or otherwise) are provided, as a contributor, you represent that the code you submit is your original work or that of your employer (in which case you represent you have the right to bind your employer). By submitting code (or otherwise providing feedback), you (and, if applicable, your employer) are licensing the submitted code (and/or feedback) to LinkedIn and the open source community subject to the BSD 2-Clause license. 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | LinkedIn Learning Exercise Files License Agreement 2 | ================================================== 3 | 4 | This License Agreement (the "Agreement") is a binding legal agreement 5 | between you (as an individual or entity, as applicable) and LinkedIn 6 | Corporation (“LinkedIn”). By downloading or using the LinkedIn Learning 7 | exercise files in this repository (“Licensed Materials”), you agree to 8 | be bound by the terms of this Agreement. If you do not agree to these 9 | terms, do not download or use the Licensed Materials. 10 | 11 | 1. License. 12 | - a. Subject to the terms of this Agreement, LinkedIn hereby grants LinkedIn 13 | members during their LinkedIn Learning subscription a non-exclusive, 14 | non-transferable copyright license, for internal use only, to 1) make a 15 | reasonable number of copies of the Licensed Materials, and 2) make 16 | derivative works of the Licensed Materials for the sole purpose of 17 | practicing skills taught in LinkedIn Learning courses. 18 | - b. Distribution. Unless otherwise noted in the Licensed Materials, subject 19 | to the terms of this Agreement, LinkedIn hereby grants LinkedIn members 20 | with a LinkedIn Learning subscription a non-exclusive, non-transferable 21 | copyright license to distribute the Licensed Materials, except the 22 | Licensed Materials may not be included in any product or service (or 23 | otherwise used) to instruct or educate others. 24 | 25 | 2. Restrictions and Intellectual Property. 26 | - a. You may not to use, modify, copy, make derivative works of, publish, 27 | distribute, rent, lease, sell, sublicense, assign or otherwise transfer the 28 | Licensed Materials, except as expressly set forth above in Section 1. 29 | - b. Linkedin (and its licensors) retains its intellectual property rights 30 | in the Licensed Materials. Except as expressly set forth in Section 1, 31 | LinkedIn grants no licenses. 32 | - c. You indemnify LinkedIn and its licensors and affiliates for i) any 33 | alleged infringement or misappropriation of any intellectual property rights 34 | of any third party based on modifications you make to the Licensed Materials, 35 | ii) any claims arising from your use or distribution of all or part of the 36 | Licensed Materials and iii) a breach of this Agreement. You will defend, hold 37 | harmless, and indemnify LinkedIn and its affiliates (and our and their 38 | respective employees, shareholders, and directors) from any claim or action 39 | brought by a third party, including all damages, liabilities, costs and 40 | expenses, including reasonable attorneys’ fees, to the extent resulting from, 41 | alleged to have resulted from, or in connection with: (a) your breach of your 42 | obligations herein; or (b) your use or distribution of any Licensed Materials. 43 | 44 | 3. Open source. This code may include open source software, which may be 45 | subject to other license terms as provided in the files. 46 | 47 | 4. Warranty Disclaimer. LINKEDIN PROVIDES THE LICENSED MATERIALS ON AN “AS IS” 48 | AND “AS AVAILABLE” BASIS. LINKEDIN MAKES NO REPRESENTATION OR WARRANTY, 49 | WHETHER EXPRESS OR IMPLIED, ABOUT THE LICENSED MATERIALS, INCLUDING ANY 50 | REPRESENTATION THAT THE LICENSED MATERIALS WILL BE FREE OF ERRORS, BUGS OR 51 | INTERRUPTIONS, OR THAT THE LICENSED MATERIALS ARE ACCURATE, COMPLETE OR 52 | OTHERWISE VALID. TO THE FULLEST EXTENT PERMITTED BY LAW, LINKEDIN AND ITS 53 | AFFILIATES DISCLAIM ANY IMPLIED OR STATUTORY WARRANTY OR CONDITION, INCLUDING 54 | ANY IMPLIED WARRANTY OR CONDITION OF MERCHANTABILITY OR FITNESS FOR A 55 | PARTICULAR PURPOSE, AVAILABILITY, SECURITY, TITLE AND/OR NON-INFRINGEMENT. 56 | YOUR USE OF THE LICENSED MATERIALS IS AT YOUR OWN DISCRETION AND RISK, AND 57 | YOU WILL BE SOLELY RESPONSIBLE FOR ANY DAMAGE THAT RESULTS FROM USE OF THE 58 | LICENSED MATERIALS TO YOUR COMPUTER SYSTEM OR LOSS OF DATA. NO ADVICE OR 59 | INFORMATION, WHETHER ORAL OR WRITTEN, OBTAINED BY YOU FROM US OR THROUGH OR 60 | FROM THE LICENSED MATERIALS WILL CREATE ANY WARRANTY OR CONDITION NOT 61 | EXPRESSLY STATED IN THESE TERMS. 62 | 63 | 5. Limitation of Liability. LINKEDIN SHALL NOT BE LIABLE FOR ANY INDIRECT, 64 | INCIDENTAL, SPECIAL, PUNITIVE, CONSEQUENTIAL OR EXEMPLARY DAMAGES, INCLUDING 65 | BUT NOT LIMITED TO, DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA OR OTHER 66 | INTANGIBLE LOSSES . IN NO EVENT WILL LINKEDIN'S AGGREGATE LIABILITY TO YOU 67 | EXCEED $100. THIS LIMITATION OF LIABILITY SHALL: 68 | - i. APPLY REGARDLESS OF WHETHER (A) YOU BASE YOUR CLAIM ON CONTRACT, TORT, 69 | STATUTE, OR ANY OTHER LEGAL THEORY, (B) WE KNEW OR SHOULD HAVE KNOWN ABOUT 70 | THE POSSIBILITY OF SUCH DAMAGES, OR (C) THE LIMITED REMEDIES PROVIDED IN THIS 71 | SECTION FAIL OF THEIR ESSENTIAL PURPOSE; AND 72 | - ii. NOT APPLY TO ANY DAMAGE THAT LINKEDIN MAY CAUSE YOU INTENTIONALLY OR 73 | KNOWINGLY IN VIOLATION OF THESE TERMS OR APPLICABLE LAW, OR AS OTHERWISE 74 | MANDATED BY APPLICABLE LAW THAT CANNOT BE DISCLAIMED IN THESE TERMS. 75 | 76 | 6. Termination. This Agreement automatically terminates upon your breach of 77 | this Agreement or termination of your LinkedIn Learning subscription. On 78 | termination, all licenses granted under this Agreement will terminate 79 | immediately and you will delete the Licensed Materials. Sections 2-7 of this 80 | Agreement survive any termination of this Agreement. LinkedIn may discontinue 81 | the availability of some or all of the Licensed Materials at any time for any 82 | reason. 83 | 84 | 7. Miscellaneous. This Agreement will be governed by and construed in 85 | accordance with the laws of the State of California without regard to conflict 86 | of laws principles. The exclusive forum for any disputes arising out of or 87 | relating to this Agreement shall be an appropriate federal or state court 88 | sitting in the County of Santa Clara, State of California. If LinkedIn does 89 | not act to enforce a breach of this Agreement, that does not mean that 90 | LinkedIn has waived its right to enforce this Agreement. The Agreement does 91 | not create a partnership, agency relationship, or joint venture between the 92 | parties. Neither party has the power or authority to bind the other or to 93 | create any obligation or responsibility on behalf of the other. You may not, 94 | without LinkedIn’s prior written consent, assign or delegate any rights or 95 | obligations under these terms, including in connection with a change of 96 | control. Any purported assignment and delegation shall be ineffective. The 97 | Agreement shall bind and inure to the benefit of the parties, their respective 98 | successors and permitted assigns. If any provision of the Agreement is 99 | unenforceable, that provision will be modified to render it enforceable to the 100 | extent possible to give effect to the parties’ intentions and the remaining 101 | provisions will not be affected. This Agreement is the only agreement between 102 | you and LinkedIn regarding the Licensed Materials, and supersedes all prior 103 | agreements relating to the Licensed Materials. 104 | 105 | Last Updated: March 2019 106 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2023 LinkedIn Corporation 2 | All Rights Reserved. 3 | 4 | Licensed under the LinkedIn Learning Exercise File License (the "License"). 5 | See LICENSE in the project root for license information. 6 | 7 | ATTRIBUTIONS: 8 | 9 | requests 10 | https://github.com/psf/requests/ 11 | License: Apache 2.0 12 | http://www.apache.org/licenses/ 13 | 14 | Please note, this project may automatically load third party code from external 15 | repositories (for example, NPM modules, Composer packages, or other dependencies). 16 | If so, such third party code may be subject to other license terms than as set 17 | forth above. In addition, such third party code may also depend on and load 18 | multiple tiers of dependencies. Please review the applicable licenses of the 19 | additional dependencies. 20 | 21 | 22 | =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= 23 | 24 | Apache License 25 | Version 2.0, January 2004 26 | http://www.apache.org/licenses/ 27 | 28 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 29 | 30 | 1. Definitions. 31 | 32 | ""License"" shall mean the terms and conditions for use, reproduction, 33 | and distribution as defined by Sections 1 through 9 of this document. 34 | 35 | ""Licensor"" shall mean the copyright owner or entity authorized by 36 | the copyright owner that is granting the License. 37 | 38 | ""Legal Entity"" shall mean the union of the acting entity and all 39 | other entities that control, are controlled by, or are under common 40 | control with that entity. For the purposes of this definition, 41 | ""control"" means (i) the power, direct or indirect, to cause the 42 | direction or management of such entity, whether by contract or 43 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 44 | outstanding shares, or (iii) beneficial ownership of such entity. 45 | 46 | ""You"" (or ""Your"") shall mean an individual or Legal Entity 47 | exercising permissions granted by this License. 48 | 49 | ""Source"" form shall mean the preferred form for making modifications, 50 | including but not limited to software source code, documentation 51 | source, and configuration files. 52 | 53 | ""Object"" form shall mean any form resulting from mechanical 54 | transformation or translation of a Source form, including but 55 | not limited to compiled object code, generated documentation, 56 | and conversions to other media types. 57 | 58 | ""Work"" shall mean the work of authorship, whether in Source or 59 | Object form, made available under the License, as indicated by a 60 | copyright notice that is included in or attached to the work 61 | (an example is provided in the Appendix below). 62 | 63 | ""Derivative Works"" shall mean any work, whether in Source or Object 64 | form, that is based on (or derived from) the Work and for which the 65 | editorial revisions, annotations, elaborations, or other modifications 66 | represent, as a whole, an original work of authorship. For the purposes 67 | of this License, Derivative Works shall not include works that remain 68 | separable from, or merely link (or bind by name) to the interfaces of, 69 | the Work and Derivative Works thereof. 70 | 71 | ""Contribution"" shall mean any work of authorship, including 72 | the original version of the Work and any modifications or additions 73 | to that Work or Derivative Works thereof, that is intentionally 74 | submitted to Licensor for inclusion in the Work by the copyright owner 75 | or by an individual or Legal Entity authorized to submit on behalf of 76 | the copyright owner. For the purposes of this definition, ""submitted"" 77 | means any form of electronic, verbal, or written communication sent 78 | to the Licensor or its representatives, including but not limited to 79 | communication on electronic mailing lists, source code control systems, 80 | and issue tracking systems that are managed by, or on behalf of, the 81 | Licensor for the purpose of discussing and improving the Work, but 82 | excluding communication that is conspicuously marked or otherwise 83 | designated in writing by the copyright owner as ""Not a Contribution."" 84 | 85 | ""Contributor"" shall mean Licensor and any individual or Legal Entity 86 | on behalf of whom a Contribution has been received by Licensor and 87 | subsequently incorporated within the Work. 88 | 89 | 2. Grant of Copyright License. Subject to the terms and conditions of 90 | this License, each Contributor hereby grants to You a perpetual, 91 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 92 | copyright license to reproduce, prepare Derivative Works of, 93 | publicly display, publicly perform, sublicense, and distribute the 94 | Work and such Derivative Works in Source or Object form. 95 | 96 | 3. Grant of Patent License. Subject to the terms and conditions of 97 | this License, each Contributor hereby grants to You a perpetual, 98 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 99 | (except as stated in this section) patent license to make, have made, 100 | use, offer to sell, sell, import, and otherwise transfer the Work, 101 | where such license applies only to those patent claims licensable 102 | by such Contributor that are necessarily infringed by their 103 | Contribution(s) alone or by combination of their Contribution(s) 104 | with the Work to which such Contribution(s) was submitted. If You 105 | institute patent litigation against any entity (including a 106 | cross-claim or counterclaim in a lawsuit) alleging that the Work 107 | or a Contribution incorporated within the Work constitutes direct 108 | or contributory patent infringement, then any patent licenses 109 | granted to You under this License for that Work shall terminate 110 | as of the date such litigation is filed. 111 | 112 | 4. Redistribution. You may reproduce and distribute copies of the 113 | Work or Derivative Works thereof in any medium, with or without 114 | modifications, and in Source or Object form, provided that You 115 | meet the following conditions: 116 | 117 | (a) You must give any other recipients of the Work or 118 | Derivative Works a copy of this License; and 119 | 120 | (b) You must cause any modified files to carry prominent notices 121 | stating that You changed the files; and 122 | 123 | (c) You must retain, in the Source form of any Derivative Works 124 | that You distribute, all copyright, patent, trademark, and 125 | attribution notices from the Source form of the Work, 126 | excluding those notices that do not pertain to any part of 127 | the Derivative Works; and 128 | 129 | (d) If the Work includes a ""NOTICE"" text file as part of its 130 | distribution, then any Derivative Works that You distribute must 131 | include a readable copy of the attribution notices contained 132 | within such NOTICE file, excluding those notices that do not 133 | pertain to any part of the Derivative Works, in at least one 134 | of the following places: within a NOTICE text file distributed 135 | as part of the Derivative Works; within the Source form or 136 | documentation, if provided along with the Derivative Works; or, 137 | within a display generated by the Derivative Works, if and 138 | wherever such third-party notices normally appear. The contents 139 | of the NOTICE file are for informational purposes only and 140 | do not modify the License. You may add Your own attribution 141 | notices within Derivative Works that You distribute, alongside 142 | or as an addendum to the NOTICE text from the Work, provided 143 | that such additional attribution notices cannot be construed 144 | as modifying the License. 145 | 146 | You may add Your own copyright statement to Your modifications and 147 | may provide additional or different license terms and conditions 148 | for use, reproduction, or distribution of Your modifications, or 149 | for any such Derivative Works as a whole, provided Your use, 150 | reproduction, and distribution of the Work otherwise complies with 151 | the conditions stated in this License. 152 | 153 | 5. Submission of Contributions. Unless You explicitly state otherwise, 154 | any Contribution intentionally submitted for inclusion in the Work 155 | by You to the Licensor shall be under the terms and conditions of 156 | this License, without any additional terms or conditions. 157 | Notwithstanding the above, nothing herein shall supersede or modify 158 | the terms of any separate license agreement you may have executed 159 | with Licensor regarding such Contributions. 160 | 161 | 6. Trademarks. This License does not grant permission to use the trade 162 | names, trademarks, service marks, or product names of the Licensor, 163 | except as required for reasonable and customary use in describing the 164 | origin of the Work and reproducing the content of the NOTICE file. 165 | 166 | 7. Disclaimer of Warranty. Unless required by applicable law or 167 | agreed to in writing, Licensor provides the Work (and each 168 | Contributor provides its Contributions) on an ""AS IS"" BASIS, 169 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 170 | implied, including, without limitation, any warranties or conditions 171 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 172 | PARTICULAR PURPOSE. You are solely responsible for determining the 173 | appropriateness of using or redistributing the Work and assume any 174 | risks associated with Your exercise of permissions under this License. 175 | 176 | 8. Limitation of Liability. In no event and under no legal theory, 177 | whether in tort (including negligence), contract, or otherwise, 178 | unless required by applicable law (such as deliberate and grossly 179 | negligent acts) or agreed to in writing, shall any Contributor be 180 | liable to You for damages, including any direct, indirect, special, 181 | incidental, or consequential damages of any character arising as a 182 | result of this License or out of the use or inability to use the 183 | Work (including but not limited to damages for loss of goodwill, 184 | work stoppage, computer failure or malfunction, or any and all 185 | other commercial damages or losses), even if such Contributor 186 | has been advised of the possibility of such damages. 187 | 188 | 9. Accepting Warranty or Additional Liability. While redistributing 189 | the Work or Derivative Works thereof, You may choose to offer, 190 | and charge a fee for, acceptance of support, warranty, indemnity, 191 | or other liability obligations and/or rights consistent with this 192 | License. However, in accepting such obligations, You may act only 193 | on Your own behalf and on Your sole responsibility, not on behalf 194 | of any other Contributor, and only if You agree to indemnify, 195 | defend, and hold each Contributor harmless for any liability 196 | incurred by, or claims asserted against, such Contributor by reason 197 | of your accepting any such warranty or additional liability." 198 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Programming Concepts for Python 2 | This is the repository for the LinkedIn Learning course `Programming Concepts for Python`. The full course is available from [LinkedIn Learning][lil-course-url]. 3 | 4 | ![Programming Concepts for Python][lil-thumbnail-url] 5 | 6 | Understanding core programming concepts and why they are used is just as important as knowing how to write code. New programmers need to learn to bridge the gap and to connect the theory to practice. In this course, Barron Stone and Olivia Chui Stone illustrate programming concepts in Python by relating them to real-life objects, actions, and scenarios. Each video focuses on a different analogy that demonstrates the concepts in code. Join Barron and Olivia as they take you through a typical Saturday and use regular tasks and errands—and even ordering pizza—to explain functions, objects, queues, sets, loops, and other programming constructs. 7 | 8 | 9 | 10 | [0]: # (Replace these placeholder URLs with actual course URLs) 11 | 12 | [lil-course-url]: https://www.linkedin.com/learning/programming-concepts-for-python 13 | [lil-thumbnail-url]: https://media.licdn.com/dms/image/D560DAQF5tQ0NTwTQ3g/learning-public-crop_675_1200/0/1698098378404?e=2147483647&v=beta&t=uBz5UeWQpQBO_64o5nbTUvXkvFYwdQRGPfT_OP34NV4 14 | 15 | -------------------------------------------------------------------------------- /examples/01_01_functions/functions_begin.py: -------------------------------------------------------------------------------- 1 | """ A Functional Breakfast """ 2 | 3 | print('Mixing the ingredients') 4 | print('Pouring the mixture into a frying pan') 5 | print('Cooking the first side') 6 | print('Flipping it!') 7 | print('Cooking the other side\n') 8 | omelette = 'a tasty omelette' 9 | -------------------------------------------------------------------------------- /examples/01_01_functions/functions_end.py: -------------------------------------------------------------------------------- 1 | """ A Functional Breakfast """ 2 | 3 | def make_omelette(): 4 | print('Mixing the ingredients') 5 | print('Pouring the mixture into a frying pan') 6 | print('Cooking the first side') 7 | print('Flipping it!') 8 | print('Cooking the other side\n') 9 | omelette = 'a tasty omelette' 10 | return omelette 11 | 12 | # make breakfast for two 13 | barron_breakfast = make_omelette() 14 | olivia_breakfast = make_omelette() 15 | print(f'Barron is having {barron_breakfast}\n') 16 | print(f'Olivia is having {olivia_breakfast}\n') 17 | -------------------------------------------------------------------------------- /examples/01_02_code_reuse/code_reuse_begin.py: -------------------------------------------------------------------------------- 1 | """ A Functional Breakfast """ 2 | 3 | def make_omelette(): 4 | print('Mixing the ingredients') 5 | print('Pouring the mixture into a frying pan') 6 | print('Cooking the first side') 7 | print('Flipping it!') 8 | print('Cooking the other side\n') 9 | omelette = 'a tasty omelette' 10 | return omelette 11 | 12 | def make_pancake(): 13 | print('Mixing the ingredients') 14 | print('Pouring the mixture into a frying pan') 15 | print('Cooking the first side') 16 | print('Flipping it!') 17 | print('Cooking the other side\n') 18 | pancake = 'a delicious pancake' 19 | return pancake 20 | 21 | # make breakfast for two 22 | barron_breakfast = make_omelette() 23 | olivia_breakfast = make_pancake() 24 | print(f'Barron is having {barron_breakfast}\n') 25 | print(f'Olivia is having {olivia_breakfast}\n') 26 | -------------------------------------------------------------------------------- /examples/01_02_code_reuse/code_reuse_end.py: -------------------------------------------------------------------------------- 1 | """ A Functional Breakfast """ 2 | 3 | def mix_and_cook(): 4 | print('Mixing the ingredients') 5 | print('Greasing the frying pan') 6 | print('Pouring the mixture into a frying pan') 7 | print('Cooking the first side') 8 | print('Flipping it!') 9 | print('Cooking the other side\n') 10 | 11 | def make_omelette(): 12 | mix_and_cook() 13 | omelette = 'a tasty omelette' 14 | return omelette 15 | 16 | def make_pancake(): 17 | mix_and_cook() 18 | pancake = 'a delicious pancake' 19 | return pancake 20 | 21 | # make breakfast for two 22 | barron_breakfast = make_omelette() 23 | olivia_breakfast = make_pancake() 24 | print(f'Barron is having {barron_breakfast}\n') 25 | print(f'Olivia is having {olivia_breakfast}\n') 26 | -------------------------------------------------------------------------------- /examples/01_03_parameters_arguments/parameters_arguments_begin.py: -------------------------------------------------------------------------------- 1 | """ A Functional Breakfast """ 2 | 3 | def mix_and_cook(): 4 | print('Mixing the ingredients') 5 | print('Greasing the frying pan') 6 | print('Pouring the mixture into a frying pan') 7 | print('Cooking the first side') 8 | print('Flipping it!') 9 | print('Cooking the other side\n') 10 | 11 | def make_omelette(): 12 | mix_and_cook() 13 | omelette = 'a tasty omelette' 14 | return omelette 15 | 16 | def make_pancake(): 17 | mix_and_cook() 18 | pancake = 'a delicious pancake' 19 | return pancake 20 | 21 | # make breakfast for two 22 | barron_breakfast = make_omelette() 23 | olivia_breakfast = make_omelette() 24 | print(f'Barron is having {barron_breakfast}\n') 25 | print(f'Olivia is having {olivia_breakfast}\n') 26 | -------------------------------------------------------------------------------- /examples/01_03_parameters_arguments/parameters_arguments_end.py: -------------------------------------------------------------------------------- 1 | """ A Functional Breakfast """ 2 | 3 | def mix_and_cook(): 4 | print('Mixing the ingredients') 5 | print('Greasing the frying pan') 6 | print('Pouring the mixture into a frying pan') 7 | print('Cooking the first side') 8 | print('Flipping it!') 9 | print('Cooking the other side\n') 10 | 11 | def make_omelette(ingredient): 12 | mix_and_cook() 13 | omelette = f'a {ingredient} omelette' 14 | return omelette 15 | 16 | def make_pancake(): 17 | mix_and_cook() 18 | pancake = 'a delicious pancake' 19 | return pancake 20 | 21 | # make breakfast for two 22 | barron_breakfast = make_omelette('bacon') 23 | olivia_breakfast = make_omelette('spam') 24 | print(f'Barron is having {barron_breakfast}\n') 25 | print(f'Olivia is having {olivia_breakfast}\n') 26 | -------------------------------------------------------------------------------- /examples/01_04_multiple_parameters/multiple_parameters_begin.py: -------------------------------------------------------------------------------- 1 | """ A Functional Breakfast """ 2 | 3 | def mix_and_cook(): 4 | print('Mixing the ingredients') 5 | print('Greasing the frying pan') 6 | print('Pouring the mixture into a frying pan') 7 | print('Cooking the first side') 8 | print('Flipping it!') 9 | print('Cooking the other side\n') 10 | 11 | def make_omelette(ingredient): 12 | mix_and_cook() 13 | omelette = f'a {ingredient} omelette' 14 | return omelette 15 | 16 | def make_pancake(): 17 | mix_and_cook() 18 | pancake = 'a delicious pancake' 19 | return pancake 20 | 21 | # make breakfast for two 22 | barron_breakfast = make_omelette('bacon') 23 | olivia_breakfast = make_omelette('spam') 24 | print(f'Barron is having {barron_breakfast}\n') 25 | print(f'Olivia is having {olivia_breakfast}\n') 26 | -------------------------------------------------------------------------------- /examples/01_04_multiple_parameters/multiple_parameters_end.py: -------------------------------------------------------------------------------- 1 | """ A Functional Breakfast """ 2 | 3 | def mix_and_cook(): 4 | print('Mixing the ingredients') 5 | print('Greasing the frying pan') 6 | print('Pouring the mixture into a frying pan') 7 | print('Cooking the first side') 8 | print('Flipping it!') 9 | print('Cooking the other side\n') 10 | 11 | def make_omelette(ingredient): 12 | mix_and_cook() 13 | omelette = f'a {ingredient} omelette' 14 | return omelette 15 | 16 | def make_pancake(): 17 | mix_and_cook() 18 | pancake = 'a delicious pancake' 19 | return pancake 20 | 21 | def make_fancy_omelette(*ingredients): 22 | mix_and_cook() 23 | omelette = f'a fancy omelette with {len(ingredients)} ingredients' 24 | return omelette 25 | 26 | # make breakfast for two 27 | barron_breakfast = make_omelette('bacon') 28 | olivia_breakfast = make_fancy_omelette('sausage', 'onion', 'pepper', 'spinach', 29 | 'mushroom', 'tomato', 'goat cheese') 30 | print(f'Barron is having {barron_breakfast}\n') 31 | print(f'Olivia is having {olivia_breakfast}\n') 32 | -------------------------------------------------------------------------------- /examples/01_05_local_global_variables/local_global_variables_begin.py: -------------------------------------------------------------------------------- 1 | """ A Functional Breakfast """ 2 | 3 | def mix_and_cook(): 4 | print('Mixing the ingredients') 5 | print('Greasing the frying pan') 6 | print('Pouring the mixture into a frying pan') 7 | print('Cooking the first side') 8 | print('Flipping it!') 9 | print('Cooking the other side\n') 10 | 11 | def make_omelette(ingredient): 12 | mix_and_cook() 13 | omelette = f'a {ingredient} omelette' 14 | return omelette 15 | 16 | def make_pancake(): 17 | mix_and_cook() 18 | pancake = 'a delicious pancake' 19 | return pancake 20 | 21 | # make breakfast for two 22 | barron_breakfast = make_omelette('bacon') 23 | olivia_breakfast = make_omelette('spam') 24 | print(f'Barron is having {barron_breakfast}\n') 25 | print(f'Olivia is having {olivia_breakfast}\n') 26 | -------------------------------------------------------------------------------- /examples/01_05_local_global_variables/local_global_variables_end.py: -------------------------------------------------------------------------------- 1 | """ A Functional Breakfast """ 2 | 3 | cheese = 'cheddar' 4 | 5 | def mix_and_cook(): 6 | print('Mixing the ingredients') 7 | print('Greasing the frying pan') 8 | print('Pouring the mixture into a frying pan') 9 | print('Cooking the first side') 10 | print('Flipping it!') 11 | print('Cooking the other side\n') 12 | 13 | def make_omelette(): 14 | global cheese 15 | cheese = 'swiss' 16 | mix_and_cook() 17 | omelette = f'a {cheese} omelette' 18 | return omelette 19 | 20 | def make_pancake(): 21 | mix_and_cook() 22 | pancake = f'a {cheese} pancake' 23 | return pancake 24 | 25 | # make breakfast for two 26 | print(f'*** global cheese is {cheese} ***\n') 27 | barron_breakfast = make_pancake() 28 | print(f'*** global cheese is {cheese} ***\n') 29 | olivia_breakfast = make_omelette() 30 | print(f'*** global cheese is {cheese} ***\n') 31 | 32 | print(f'Barron is having {barron_breakfast}\n') 33 | print(f'Olivia is having {olivia_breakfast}\n') 34 | -------------------------------------------------------------------------------- /examples/02_01_objects/objects_commands.py: -------------------------------------------------------------------------------- 1 | """ What Makes Up an Object? """ 2 | 3 | # Demo Commands(with print() functions to show output when run as main script) 4 | 5 | # examine a string object 6 | print('shirt') 7 | print(type('shirt')) 8 | print(dir('shirt')) 9 | 10 | # use upper method on a string object 11 | print('shirt'.upper()) 12 | 13 | # examine IDs of different string objects 14 | print(id('shirt')) 15 | print(id('pants')) 16 | 17 | # examine an integer object 18 | print(id(1)) 19 | print(dir(1)) 20 | 21 | # examine ID and attributes of functions 22 | print(id(id)) 23 | print(dir(dir)) 24 | -------------------------------------------------------------------------------- /examples/02_02_classes/classes_begin.py: -------------------------------------------------------------------------------- 1 | """ The Blueprint for Jeans """ 2 | 3 | class Jeans: 4 | def __init__(self, waist, length, color): 5 | self.waist = waist 6 | self.length = length 7 | self.color = color 8 | self.wearing = False 9 | 10 | def put_on(self): 11 | print(f'Putting on {self.waist}x{self.length} {self.color} jeans') 12 | self.wearing = True 13 | 14 | def take_off(self): 15 | print(f'Taking off {self.waist}x{self.length} {self.color} jeans') 16 | self.wearing = False 17 | -------------------------------------------------------------------------------- /examples/02_02_classes/classes_end.py: -------------------------------------------------------------------------------- 1 | """ The Blueprints for Jeans """ 2 | 3 | class Jeans: 4 | def __init__(self, waist, length, color): 5 | self.waist = waist 6 | self.length = length 7 | self.color = color 8 | self.wearing = False 9 | 10 | def put_on(self): 11 | print(f'Putting on {self.waist}x{self.length} {self.color} jeans') 12 | self.wearing = True 13 | 14 | def take_off(self): 15 | print(f'Taking off {self.waist}x{self.length} {self.color} jeans') 16 | self.wearing = False 17 | 18 | # Demo Commands(with print() functions to show output when run as main script) 19 | if __name__ == '__main__': 20 | 21 | # create and examine a pair of jeans 22 | my_jeans = Jeans(31, 32, 'blue') 23 | print(type(my_jeans)) 24 | print(dir(my_jeans)) 25 | 26 | # don and remove the jeans 27 | my_jeans.put_on() 28 | print(my_jeans.wearing) 29 | 30 | my_jeans.take_off() 31 | print(my_jeans.wearing) 32 | -------------------------------------------------------------------------------- /examples/02_03_object_names/object_names_begin.py: -------------------------------------------------------------------------------- 1 | """ Two Names, One Shirt """ 2 | 3 | class Shirt: 4 | def __init__(self): 5 | self.clean = True 6 | 7 | def make_dirty(self): 8 | self.clean = False 9 | 10 | def make_clean(self): 11 | self.clean = True 12 | -------------------------------------------------------------------------------- /examples/02_03_object_names/object_names_end.py: -------------------------------------------------------------------------------- 1 | """ Two Names, One Shirt """ 2 | 3 | class Shirt: 4 | def __init__(self): 5 | self.clean = True 6 | 7 | def make_dirty(self): 8 | self.clean = False 9 | 10 | def make_clean(self): 11 | self.clean = True 12 | 13 | # Demo Commands(with print() functions to show output when run as main script) 14 | if __name__ == '__main__': 15 | 16 | # create one shirt with two names 17 | red = Shirt() 18 | crimson = red 19 | 20 | # examine the red/crimson shirt 21 | print(id(red)) 22 | print(id(crimson)) 23 | print(red.clean) 24 | print(crimson.clean) 25 | 26 | # spill juice on the red/crimson shirt 27 | red.make_dirty() 28 | print(red.clean) 29 | print(crimson.clean) 30 | 31 | # check that red and crimson are the same shirt 32 | print(red is crimson) 33 | 34 | # create a second shirt to be named crimson 35 | crimson = Shirt() 36 | 37 | # examine both shirts 38 | print(id(red)) 39 | print(id(crimson)) 40 | print(crimson.clean) 41 | print(red.clean) 42 | 43 | # clean the red shirt 44 | red.make_clean() 45 | print(red.clean) 46 | print(crimson.clean) 47 | 48 | # check that red and crimson are different shirts 49 | print(red is crimson) 50 | -------------------------------------------------------------------------------- /examples/02_04_mutability/mutability_commands.py: -------------------------------------------------------------------------------- 1 | """ You Can Change an Outfit, But You Can't Change Your Words """ 2 | 3 | # Demo Commands(with print() functions to show output when run as main script) 4 | 5 | # create a closet full of clothes 6 | closet = ['shirt', 'hat', 'pants', 'jacket', 'socks'] 7 | print(closet) 8 | print(id(closet)) 9 | 10 | # remove a hat 11 | closet.remove('hat') 12 | print(closet) 13 | print(id(closet)) 14 | 15 | # create a poor choice of words 16 | words = "You're wearing that" 17 | print(words) 18 | print(id(words)) 19 | 20 | # add more to the phrase 21 | words = words + ' because you look great!' 22 | print(words) 23 | print(id(words)) 24 | -------------------------------------------------------------------------------- /examples/03_01_inheritance/inheritance_begin.py: -------------------------------------------------------------------------------- 1 | """ A Garage Full of Classy Vehicles """ 2 | 3 | # Base Vehicle class 4 | class Vehicle: 5 | def __init__(self, color, manufacturer): 6 | self.color = color 7 | self.manufacturer = manufacturer 8 | self.gas = 4 # a full tank of gas 9 | 10 | def drive(self): 11 | if self.gas > 0: 12 | self.gas -= 1 13 | print(f'The {self.color} {self.manufacturer} goes VROOOM!!!') 14 | else: 15 | print(f'The {self.color} {self.manufacturer} sputters out of gas...') 16 | 17 | # Car inherits the Vehicle class 18 | class Car(Vehicle): 19 | def radio(self): # turn on the radio 20 | print("Rockin' Tunes!") 21 | 22 | def window(self): # open the window 23 | print('Ahhh... fresh air!') 24 | 25 | # Motorcycle inherits the Vehicle class 26 | class Motorcycle(Vehicle): 27 | def helmet(self): # put on a helmet 28 | print('Helmet on - nice and safe!') 29 | -------------------------------------------------------------------------------- /examples/03_01_inheritance/inheritance_end.py: -------------------------------------------------------------------------------- 1 | """ A Garage Full of Classy Vehicles """ 2 | 3 | # Base Vehicle class 4 | class Vehicle: 5 | def __init__(self, color, manufacturer): 6 | self.color = color 7 | self.manufacturer = manufacturer 8 | self.gas = 4 # a full tank of gas 9 | 10 | def drive(self): 11 | if self.gas > 0: 12 | self.gas -= 1 13 | print(f'The {self.color} {self.manufacturer} goes VROOOM!!!') 14 | else: 15 | print(f'The {self.color} {self.manufacturer} sputters out of gas...') 16 | 17 | # Car inherits the Vehicle class 18 | class Car(Vehicle): 19 | def radio(self): # turn on the radio 20 | print("Rockin' Tunes!") 21 | 22 | def window(self): # open the window 23 | print('Ahhh... fresh air!') 24 | 25 | # Motorcycle inherits the Vehicle class 26 | class Motorcycle(Vehicle): 27 | def helmet(self): # put on a helmet 28 | print('Helmet on - nice and safe!') 29 | 30 | 31 | # Demo Commands(with print() functions to show output when run as main script) 32 | if __name__ == '__main__': 33 | 34 | # create car & motorcycle objects 35 | my_car = Car('red', 'Mercedes') 36 | my_mc = Motorcycle('silver', 'Harley') 37 | 38 | # take them out for a test drive 39 | my_car.drive() 40 | my_mc.drive() 41 | my_mc.drive() 42 | my_mc.drive() 43 | my_mc.drive() 44 | my_mc.drive() # out of gas 45 | my_car.drive() 46 | 47 | # play around with accessories 48 | my_car.radio() 49 | my_car.window() 50 | my_mc.helmet() 51 | # my_mc.window() # windows do not exist on motorcycles - throws and error 52 | -------------------------------------------------------------------------------- /examples/03_02_overriding/overriding_begin.py: -------------------------------------------------------------------------------- 1 | """ A Garage Full of Classy Vehicles """ 2 | 3 | # Base Vehicle class 4 | class Vehicle: 5 | def __init__(self, color, manufacturer): 6 | self.color = color 7 | self.manufacturer = manufacturer 8 | self.gas = 4 # a full tank of gas 9 | 10 | def drive(self): 11 | if self.gas > 0: 12 | self.gas -= 1 13 | print(f'The {self.color} {self.manufacturer} goes VROOOM!!!') 14 | else: 15 | print(f'The {self.color} {self.manufacturer} sputters out of gas...') 16 | 17 | # Car inherits the Vehicle class 18 | class Car(Vehicle): 19 | def radio(self): # turn on the radio 20 | print("Rockin' Tunes!") 21 | 22 | def window(self): # open the window 23 | print('Ahhh... fresh air!') 24 | 25 | # Motorcycle inherits the Vehicle class 26 | class Motorcycle(Vehicle): 27 | def helmet(self): # put on a helmet 28 | print('Helmet on - nice and safe!') 29 | -------------------------------------------------------------------------------- /examples/03_02_overriding/overriding_end.py: -------------------------------------------------------------------------------- 1 | """ A Garage Full of Classy Vehicles """ 2 | 3 | # Base Vehicle class 4 | class Vehicle: 5 | def __init__(self, color, manufacturer): 6 | self.color = color 7 | self.manufacturer = manufacturer 8 | self.gas = 4 # a full tank of gas 9 | 10 | def drive(self): 11 | if self.gas > 0: 12 | self.gas -= 1 13 | print(f'The {self.color} {self.manufacturer} goes VROOOM!!!') 14 | else: 15 | print(f'The {self.color} {self.manufacturer} sputters out of gas...') 16 | 17 | # Car inherits the Vehicle class 18 | class Car(Vehicle): 19 | def radio(self): # turn on the radio 20 | print("Rockin' Tunes!") 21 | 22 | def window(self): # open the window 23 | print('Ahhh... fresh air!') 24 | 25 | # Motorcycle inherits the Vehicle class 26 | class Motorcycle(Vehicle): 27 | def helmet(self): # put on a helmet 28 | print('Helmet on - nice and safe!') 29 | 30 | # ECar inherits the Car class 31 | class ECar(Car): 32 | def drive(self): # an eco-friendly drive method 33 | print(f'The {self.color} {self.manufacturer} goes ssshhh...') 34 | 35 | 36 | # Demo Commands(with print() functions to show output when run as main script) 37 | if __name__ == '__main__': 38 | 39 | # create and use an electric car 40 | my_ecar = ECar('white', 'Nissan') 41 | my_ecar.window() 42 | my_ecar.radio() 43 | my_ecar.drive() 44 | 45 | # access the lingering gas tank 46 | print(my_ecar.gas) 47 | -------------------------------------------------------------------------------- /examples/04_01_modules/modules_commands.py: -------------------------------------------------------------------------------- 1 | """ The Right Tools for the Job """ 2 | 3 | # Demo Commands(with print() functions to show output when run as main script) 4 | 5 | # import the entire random module 6 | import random 7 | print(random.randint(1,20)) 8 | # randint(1,20) # causes an error 9 | 10 | # import just the randint function 11 | from random import randint 12 | print(randint(1,20)) 13 | print(random.random()) 14 | 15 | # import just the random function 16 | from random import random 17 | print(random()) 18 | # random.randint(1,20) # causes an error 19 | 20 | # import the entire random module as "random" 21 | import random as rand 22 | print(rand.randint(1,20)) 23 | print(random()) 24 | -------------------------------------------------------------------------------- /examples/04_02_packages/packages_commands.py: -------------------------------------------------------------------------------- 1 | """ The Hierarchy of Packages """ 2 | 3 | # Demo Commands(with print() functions to show output when run as main script) 4 | 5 | import urllib.request 6 | 7 | # retrieve google.com home page 8 | print(urllib.request.urlopen('http://www.google.com')) 9 | 10 | # get the path to urllib package 11 | print(urllib.__path__) 12 | -------------------------------------------------------------------------------- /examples/05_01_lists/lists_commands.py: -------------------------------------------------------------------------------- 1 | """ Parking Cars in a List """ 2 | 3 | # Demo Commands(with print() functions to show output when run as main script) 4 | 5 | # create the initial list of cars 6 | row = ['Ford', 'Audi', 'BMW', 'Lexus'] 7 | 8 | # park a Mercedes at the end of the row 9 | row.append('Mercedes') 10 | print(row) 11 | print(row[4]) 12 | 13 | # swap a BMW at index 2 for a Jeep 14 | row[2] = 'Jeep' 15 | print(row) 16 | 17 | # park a Honda at the end of the row 18 | row.append('Honda') 19 | print(row) 20 | print(row[4]) 21 | 22 | # park a Kia at the front of the row 23 | row.insert(0, 'Kia') 24 | print(row) 25 | print(row[4]) 26 | 27 | # find the Mercedes and leave the list 28 | print(row.index('Mercedes')) 29 | print(row.pop(5)) 30 | print(row) 31 | 32 | # find and remove a Lexus 33 | row.remove('Lexus') 34 | print(row) 35 | -------------------------------------------------------------------------------- /examples/05_02_multidimensional_lists/multidimensional_lists_begin.py: -------------------------------------------------------------------------------- 1 | """ A 3-Dimensional Valet Service """ 2 | 3 | # 2D list of lists - index cars by row, spot 4 | lot_2d = [['Toyota', 'Audi', 'BMW'], # 0th row 5 | ['Lexus', 'Jeep'], # 1st row 6 | ['Honda', 'Kia', 'Mazda']] # 2nd row 7 | 8 | # 3D list of lists of lists - index cars by floor, row, spot 9 | lot_3d = [[['Telsa', 'Fiat', 'BMW'], # 0th floor 10 | ['Honda', 'Jeep'], 11 | ['Saab', 'Kia', 'Ford']], 12 | [['Subaru', 'Nissan'], # 1st floor 13 | ['Volvo']], 14 | [['Mazda', 'Chevy'], # 2nd floor 15 | [], 16 | ['Volkswagen']]] 17 | -------------------------------------------------------------------------------- /examples/05_02_multidimensional_lists/multidimensional_lists_commands.py: -------------------------------------------------------------------------------- 1 | """ A 3-Dimensional Valet Service """ 2 | 3 | # 2D list of lists - index cars by row, spot 4 | lot_2d = [['Toyota', 'Audi', 'BMW'], # 0th row 5 | ['Lexus', 'Jeep'], # 1st row 6 | ['Honda', 'Kia', 'Mazda']] # 2nd row 7 | 8 | # 3D list of lists of lists - index cars by floor, row, spot 9 | lot_3d = [[['Telsa', 'Fiat', 'BMW'], # 0th floor 10 | ['Honda', 'Jeep'], 11 | ['Saab', 'Kia', 'Ford']], 12 | [['Subaru', 'Nissan'], # 1st floor 13 | ['Volvo']], 14 | [['Mazda', 'Chevy'], # 2nd floor 15 | [], 16 | ['Volkswagen']]] 17 | 18 | """ Demo Commands (with print() functions to show output when run as main script) """ 19 | if __name__ == '__main__': 20 | 21 | # indexing 2D lists 22 | print(lot_2d) # 2D list of parking lot 23 | print(lot_2d[2]) # 1D list of cars in row 2 24 | print(lot_2d[2][1]) # car parking in row 2, spot 1 25 | 26 | # indexing 3D lists 27 | print(lot_3d) # 3D list of multi-story garage 28 | print(lot_3d[0]) # 2D list of cars on floor 0 29 | print(lot_3d[0][2]) # 1D list of cars on floor 0, row 2 30 | print(lot_3d[0][2][1]) # car parked on floor 0, row 2, spot 1 31 | 32 | # accessing all cars in the multi-story garage 33 | for floor in lot_3d: # cycle through each floor in the multi-story garage 34 | for row in floor: # cycle through each row in the floor 35 | for car in row: # cycle through each car in the row 36 | print(car) 37 | -------------------------------------------------------------------------------- /examples/05_03_tuples/tuples_commands.py: -------------------------------------------------------------------------------- 1 | """ A simple tuple""" 2 | 3 | # Demo Commands (with print() functions to show output when run as main script) 4 | 5 | my_tuple = ('a', 'b', 'c', 1, 2, 3) # create tuple 6 | print(my_tuple) # display entire tuple 7 | print(my_tuple[2]) # index and display a single element 8 | my_tuple[2] = 'd' # attempt to modify the tuple - throws an error 9 | -------------------------------------------------------------------------------- /examples/06_01_queues/queues_commands.py: -------------------------------------------------------------------------------- 1 | """ A Queue of Groceries to Put Away """ 2 | 3 | # Demo Commands (with print() functions to show output when run as main script) 4 | 5 | # create a new queue object 6 | import queue 7 | q = queue.Queue() 8 | print(q.empty()) 9 | 10 | # put bags into the queue 11 | q.put('bag1') 12 | print(q.empty()) 13 | q.put('bag2') 14 | q.put('bag3') 15 | 16 | # get bags from the queue in FIFO order 17 | print(q.get()) 18 | print(q.get()) 19 | print(q.get()) 20 | # q.get() # causes an error; use CTRL+C to 21 | 22 | # create a new queue to hold two items 23 | q2 = queue.Queue(maxsize=2) 24 | print(q2.empty()) 25 | 26 | # put two bags into the two-item queue 27 | q2.put('bag1') 28 | print(q2.full()) 29 | q2.put('bag2') 30 | print(q2.full()) 31 | 32 | # try to put an extra bag into the queue 33 | q2.put_nowait('bag3') # causes an error 34 | -------------------------------------------------------------------------------- /examples/06_02_stacks/stacks_commands.py: -------------------------------------------------------------------------------- 1 | """ A Stack of Bills to Pay """ 2 | 3 | # Demo Commands (with print() functions to show output when run as main script) 4 | 5 | # create a list to use as the stack 6 | stack = list() 7 | 8 | # add some bills to the stack 9 | stack.append('bill1') 10 | stack.append('bill2') 11 | 12 | # remove the top bill to pay it 13 | print(stack.pop()) 14 | 15 | # add two more bills to the stack 16 | stack.append('bill3') 17 | stack.append('bill4') 18 | 19 | # remove bills from top to bottom 20 | print(stack.pop()) 21 | print(stack.pop()) 22 | print(stack.pop()) 23 | stack.pop() # causes Indexerror exception 24 | -------------------------------------------------------------------------------- /examples/07_01_create_combine_sets/create_combine_sets_begin.py: -------------------------------------------------------------------------------- 1 | """ Creating and Combining Sets of Friends """ 2 | 3 | college = set(['Bill', 'Katy', 'Verne', 'Dillon', 4 | 'Bruce', 'Olivia', 'Richard', 'Jim']) 5 | 6 | coworker = set(['Aaron', 'Bill', 'Brandon', 'David', 7 | 'Frank', 'Connie', 'Kyle', 'Olivia']) 8 | 9 | family = set(['Garry', 'Landon', 'Larry', 'Mark', 10 | 'Olivia', 'Katy', 'Rae', 'Tom']) 11 | -------------------------------------------------------------------------------- /examples/07_01_create_combine_sets/create_combine_sets_end.py: -------------------------------------------------------------------------------- 1 | """ Creating and Combining Sets of Friends """ 2 | 3 | college = set(['Bill', 'Katy', 'Verne', 'Dillon', 4 | 'Bruce', 'Olivia', 'Richard', 'Jim']) 5 | 6 | coworker = set(['Aaron', 'Bill', 'Brandon', 'David', 7 | 'Frank', 'Connie', 'Kyle', 'Olivia']) 8 | 9 | family = set(['Garry', 'Landon', 'Larry', 'Mark', 10 | 'Olivia', 'Katy', 'Rae', 'Tom']) 11 | 12 | # Demo Commands (with print() functions to show output when run as main script) 13 | if __name__ == '__main__': 14 | 15 | # display all of the items in the college set 16 | print(college) 17 | 18 | # check the number of items in each set 19 | print(len(college)) 20 | print(len(coworker)) 21 | print(len(family)) 22 | 23 | # combine all friends into a single set 24 | friends = college.union(coworker, family) 25 | 26 | # print out friends in each set 27 | print(f'I have {len(college)} college buddies named:\n{college}\n') 28 | print(f'I have {len(coworker)} coworkers named:\n{coworker}\n') 29 | print(f'I have {len(family)} family friends named:\n{family}\n') 30 | print(f'I have {len(friends)} total friends named:\n{friends}\n') 31 | -------------------------------------------------------------------------------- /examples/07_02_sort_sets/sort_sets_begin.py: -------------------------------------------------------------------------------- 1 | """ Sorting Friends into Sets """ 2 | 3 | # set of all friends 4 | friends = set(['Mark', 'Rae', 'Verne', 'Richard', 5 | 'Aaron', 'David', 'Bruce', 'Garry', 6 | 'Bill', 'Connie', 'Larry', 'Jim', 7 | 'Landon', 'Dillon', 'Frank', 'Tom', 8 | 'Kyle', 'Katy', 'Olivia', 'Brandon']) 9 | 10 | # set of people who live in my zip code 11 | zipcode = set(['Jerry', 'Elaine', 'Cindy', 'Verne', 12 | 'Rudolph', 'Bill', 'Olivia', 'Jim', 13 | 'Lindsay', 'Rae', 'Mark', 'Kramer', 14 | 'Landon', 'Newman', 'George']) 15 | 16 | # set of people who play Munchkin 17 | munchkins = set(['Steve', 'Jackson', 'Frank', 'Bill', 18 | 'Mark', 'Landon', 'Rae']) 19 | 20 | # set of Olivia's friends 21 | olivia = set(['Jim', 'Amanda', 'Verne', 'Nestor']) 22 | -------------------------------------------------------------------------------- /examples/07_02_sort_sets/sort_sets_end.py: -------------------------------------------------------------------------------- 1 | """ Sorting Friends into Sets """ 2 | 3 | # set of all friends 4 | friends = set(['Mark', 'Rae', 'Verne', 'Richard', 5 | 'Aaron', 'David', 'Bruce', 'Garry', 6 | 'Bill', 'Connie', 'Larry', 'Jim', 7 | 'Landon', 'Dillon', 'Frank', 'Tom', 8 | 'Kyle', 'Katy', 'Olivia', 'Brandon']) 9 | 10 | # set of people who live in my zip code 11 | zipcode = set(['Jerry', 'Elaine', 'Cindy', 'Verne', 12 | 'Rudolph', 'Bill', 'Olivia', 'Jim', 13 | 'Lindsay', 'Rae', 'Mark', 'Kramer', 14 | 'Landon', 'Newman', 'George']) 15 | 16 | # set of people who play Munchkin 17 | munchkins = set(['Steve', 'Jackson', 'Frank', 'Bill', 18 | 'Mark', 'Landon', 'Rae']) 19 | 20 | # set of Olivia's friends 21 | olivia = set(['Jim', 'Amanda', 'Verne', 'Nestor']) 22 | 23 | # Demo Commands (with print() functions to show output when run as main script) 24 | if __name__ == '__main__': 25 | 26 | # choose just the friends who live nearby 27 | local = friends.intersection(zipcode) 28 | print(f'I have {len(local)} local friends named:\n{local}\n') 29 | 30 | # remove the Munchkin players 31 | invite = local.difference(munchkins) 32 | print(f'I have {len(invite)} friends to invite named:\n{invite}\n') 33 | 34 | # revise the friends to invite set 35 | invite = invite.symmetric_difference(olivia) 36 | print(f'My revised set has {len(invite)} friends named:\n{invite}\n') 37 | -------------------------------------------------------------------------------- /examples/07_03_add_remove_sets/add_remove_sets_begin.py: -------------------------------------------------------------------------------- 1 | """ Adding and Removing Friends from Sets """ 2 | 3 | # revised set of friends to invite 4 | invite = set(['Nestor', 'Amanda', 'Olivia']) 5 | -------------------------------------------------------------------------------- /examples/07_03_add_remove_sets/add_remove_sets_end.py: -------------------------------------------------------------------------------- 1 | """ Adding and Removing Friends from Sets """ 2 | 3 | # revised set of friends to invite 4 | invite = set(['Nestor', 'Amanda', 'Olivia']) 5 | 6 | # Demo Commands (with print() functions to show output when run as main script) 7 | if __name__ == '__main__': 8 | 9 | # invite Verne 10 | print('Verne' in invite) 11 | invite.add('Verne') 12 | print(invite) 13 | 14 | # make sure Olivia is invited 15 | invite.add('Olivia') 16 | print(invite) 17 | 18 | # remove Nestor from invite set 19 | invite.remove('Nestor') 20 | print(invite) 21 | # invite.remove('Nestor') # will throw an error 22 | 23 | # start inviting friends 24 | print(invite.pop()) 25 | print(invite.pop()) 26 | print(invite.pop()) 27 | print(invite.pop()) # will throw an error 28 | -------------------------------------------------------------------------------- /examples/08_01_dictionaries/dictionaries_begin.py: -------------------------------------------------------------------------------- 1 | """ A Rolodex Full of Friends """ 2 | 3 | # dictionary of name/number pairs 4 | rolodex = {'Aaron': 5556069, 5 | 'Bill': 5559824, 6 | 'Dad': 5552603, 7 | 'David': 5558331, 8 | 'Dillon': 5553538, 9 | 'Jim': 5555547, 10 | 'Mom': 5552603, 11 | 'Olivia': 5556397, 12 | 'Verne': 5555309} 13 | -------------------------------------------------------------------------------- /examples/08_01_dictionaries/dictionaries_end.py: -------------------------------------------------------------------------------- 1 | """ A Rolodex Full of Friends """ 2 | 3 | # dictionary of name/number pairs 4 | rolodex = {'Aaron': 5556069, 5 | 'Bill': 5559824, 6 | 'Dad': 5552603, 7 | 'David': 5558331, 8 | 'Dillon': 5553538, 9 | 'Jim': 5555547, 10 | 'Mom': 5552603, 11 | 'Olivia': 5556397, 12 | 'Verne': 5555309} 13 | 14 | # Demo Commands(with print() functions to show output when run as main script) 15 | if __name__ == '__main__': 16 | 17 | # look up Verne's number 18 | print(rolodex['Verne']) 19 | 20 | # look at hash value of 'Verne' 21 | print(hash('Verne')) 22 | -------------------------------------------------------------------------------- /examples/08_02_add_to_dictionaries/add_to_dictionaries_begin.py: -------------------------------------------------------------------------------- 1 | """ A Rolodex Full of Friends """ 2 | 3 | # dictionary of name/number pairs 4 | rolodex = {'Aaron': 5556069, 5 | 'Bill': 5559824, 6 | 'Dad': 5552603, 7 | 'David': 5558331, 8 | 'Dillon': 5553538, 9 | 'Jim': 5555547, 10 | 'Mom': 5552603, 11 | 'Olivia': 5556397, 12 | 'Verne': 5555309} 13 | -------------------------------------------------------------------------------- /examples/08_02_add_to_dictionaries/add_to_dictionaries_end.py: -------------------------------------------------------------------------------- 1 | """ A Rolodex Full of Friends """ 2 | 3 | # dictionary of name/number pairs 4 | rolodex = {'Aaron': 5556069, 5 | 'Bill': 5559824, 6 | 'Dad': 5552603, 7 | 'David': 5558331, 8 | 'Dillon': 5553538, 9 | 'Jim': 5555547, 10 | 'Mom': 5552603, 11 | 'Olivia': 5556397, 12 | 'Verne': 5555309} 13 | 14 | # Demo Commands(with print() functions to show output when run as main script) 15 | if __name__ == '__main__': 16 | 17 | # look for Amanda (not in rolodex) 18 | # print(rolodex['Amanda']) # causes an error 19 | 20 | # add Amanda to the rolodex 21 | rolodex['Amanda'] = 5559754 22 | print(rolodex['Amanda']) 23 | 24 | # overwrite David's number 25 | print(rolodex['David']) 26 | rolodex['David'] = 5550902 27 | print(rolodex['David']) 28 | 29 | # store a tuple with both numbers 30 | rolodex['David'] = (5558331, 5550902) 31 | print(rolodex['David']) 32 | 33 | # store each David's number with a unique key 34 | rolodex['David'] = 5558331 35 | rolodex['David (Amanda)'] = 5550902 36 | print(rolodex['David']) 37 | print(rolodex['David (Amanda)']) 38 | -------------------------------------------------------------------------------- /examples/08_03_reverse_lookup/reverse_lookup_begin.py: -------------------------------------------------------------------------------- 1 | """ A Rolodex Full of Friends """ 2 | 3 | # dictionary of name/number pairs 4 | rolodex = {'Aaron': 5556069, 5 | 'Bill': 5559824, 6 | 'Dad': 5552603, 7 | 'David': 5558331, 8 | 'Dillon': 5553538, 9 | 'Jim': 5555547, 10 | 'Mom': 5552603, 11 | 'Olivia': 5556397, 12 | 'Verne': 5555309} 13 | -------------------------------------------------------------------------------- /examples/08_03_reverse_lookup/reverse_lookup_end.py: -------------------------------------------------------------------------------- 1 | """ A Rolodex Full of Friends """ 2 | 3 | # dictionary of name/number pairs 4 | rolodex = {'Aaron': 5556069, 5 | 'Bill': 5559824, 6 | 'Dad': 5552603, 7 | 'David': 5558331, 8 | 'Dillon': 5553538, 9 | 'Jim': 5555547, 10 | 'Mom': 5552603, 11 | 'Olivia': 5556397, 12 | 'Verne': 5555309} 13 | 14 | def caller_id(lookup_number): 15 | for name, number in rolodex.items(): 16 | if number == lookup_number: 17 | return name 18 | 19 | # Demo Commands(with print() functions to show output when run as main script) 20 | if __name__ == '__main__': 21 | 22 | # reverse-lookup Olivia's number 23 | print(caller_id(5556397)) 24 | 25 | # reverse-lookup a number not in the rolodex 26 | print(caller_id(8675309)) 27 | 28 | # reverse-lookup number for Dad & Mom 29 | print(caller_id(5552603)) 30 | -------------------------------------------------------------------------------- /examples/09_01_if_else_statements/if_else_statement_begin.py: -------------------------------------------------------------------------------- 1 | """ Ordering A Pizza That Verne Can Eat """ 2 | 3 | # things that Verne does not eat 4 | diet_restrictions = set(['meat', 'cheese']) 5 | 6 | # decide which pizza to order 7 | if 'meat' in diet_restrictions: 8 | print('Get a cheese pizza.') 9 | 10 | elif 'meat' and 'cheese' in diet_restrictions: 11 | print('Get a vegan pizza.') 12 | 13 | else: 14 | print('Get something else.') 15 | -------------------------------------------------------------------------------- /examples/09_01_if_else_statements/if_else_statement_end.py: -------------------------------------------------------------------------------- 1 | """ Ordering A Pizza That Verne Can Eat """ 2 | 3 | # things that Verne does not eat 4 | diet_restrictions = set(['meat', 'cheese']) 5 | 6 | # decide which pizza to order 7 | if 'meat' and 'cheese' in diet_restrictions: 8 | print('Get a vegan pizza.') 9 | 10 | elif 'meat' in diet_restrictions: 11 | print('Get a cheese pizza.') 12 | 13 | else: 14 | print('Get something else.') 15 | -------------------------------------------------------------------------------- /examples/09_02_match_statements/match_statements_begin.py: -------------------------------------------------------------------------------- 1 | """ I'll Have the Special! """ 2 | 3 | def order_special(day): 4 | match day: 5 | case 'Sunday': 6 | return 'spinach pizza' 7 | case 'Monday': 8 | return 'mushroom pizza' 9 | case 'Tuesday': 10 | return 'pepperoni pizza' 11 | case 'Wednesday': 12 | return 'veggie pizza' 13 | case 'Thursday': 14 | return 'bbq chicken pizza' 15 | case 'Friday': 16 | return 'sausage pizza' 17 | case 'Saturday': 18 | return 'Hawaiian pizza' 19 | 20 | today = 'Tuesday' 21 | special = order_special(today) 22 | print(f'\nToday is {today}, and the special is {special}.\n') 23 | -------------------------------------------------------------------------------- /examples/09_02_match_statements/match_statements_end.py: -------------------------------------------------------------------------------- 1 | """ I'll Have the Special! """ 2 | 3 | def order_special(day): 4 | match day: 5 | case 'Sunday': 6 | return 'spinach pizza' 7 | case 'Monday': 8 | return 'mushroom pizza' 9 | case 'Tuesday': 10 | return 'pepperoni pizza' 11 | case 'Wednesday': 12 | return 'veggie pizza' 13 | case 'Thursday': 14 | return 'bbq chicken pizza' 15 | case _: 16 | print(f'There is no {day} special.') 17 | return None 18 | 19 | today = 'Christmas' 20 | special = order_special(today) 21 | print(f'\nToday is {today}, and the special is {special}.\n') 22 | -------------------------------------------------------------------------------- /examples/10_01_for_loops/for_loops_begin.py: -------------------------------------------------------------------------------- 1 | """ Loading the Dishwasher """ 2 | 3 | # dirty dishes in the sink 4 | sink = ['bowl', 'plate', 'cup'] 5 | print(f'\nThere are {len(sink)} dishes in the sink: {sink}\n') 6 | 7 | for dish in sink: 8 | print(f' - Put a {dish} in the dishwasher') 9 | 10 | # check that the sink is empty 11 | print(f'\nThere are {len(sink)} dishes in the sink: {sink}\n') 12 | -------------------------------------------------------------------------------- /examples/10_01_for_loops/for_loops_end.py: -------------------------------------------------------------------------------- 1 | """ Loading the Dishwasher """ 2 | 3 | # dirty dishes in the sink 4 | sink = ['bowl', 'plate', 'cup'] 5 | print(f'\nThere are {len(sink)} dishes in the sink: {sink}\n') 6 | 7 | for dish in list(sink): 8 | print(f' - Put a {dish} in the dishwasher') 9 | sink.remove(dish) 10 | 11 | # check that the sink is empty 12 | print(f'\nThere are {len(sink)} dishes in the sink: {sink}\n') 13 | -------------------------------------------------------------------------------- /examples/10_02_while_loops/while_loops_begin.py: -------------------------------------------------------------------------------- 1 | """ Scrubbing A Stuborn Pan """ 2 | 3 | import random 4 | 5 | dirty = True # state of the pan 6 | scrub_count = 0 # number of scrubs 7 | 8 | while dirty: 9 | scrub_count += 1 10 | print(f'Scrubbed the pan {scrub_count} times.') 11 | 12 | print('Rinsing to check if the pan is clean...\n') 13 | 14 | if not random.randint(0, 9): 15 | print('All clean!') 16 | dirty = False 17 | else: 18 | print('Still dirty...') 19 | -------------------------------------------------------------------------------- /examples/10_02_while_loops/while_loops_end.py: -------------------------------------------------------------------------------- 1 | """ Scrubbing A Stuborn Pan """ 2 | 3 | import random 4 | 5 | dirty = True # state of the pan 6 | scrub_count = 0 # number of scrubs 7 | 8 | while dirty: 9 | scrub_count += 1 10 | print(f'Scrubbed the pan {scrub_count} times.') 11 | 12 | if not random.randint(0, 9): 13 | print('All clean!') 14 | dirty = False 15 | else: 16 | print('Still dirty...') 17 | 18 | print('Rinsing to check if the pan is clean...\n') 19 | -------------------------------------------------------------------------------- /examples/10_03_for_break/for_break_begin.py: -------------------------------------------------------------------------------- 1 | """ Putting Away Clean Dishes """ 2 | 3 | import random 4 | 5 | # 20 clean dishes in dishwasher 6 | dishwasher = ['plate', 'bowl', 'cup', 'knife', 'fork', 7 | 'spoon', 'plate', 'spoon', 'bowl', 'cup', 8 | 'knife', 'cup', 'cup', 'fork', 'bowl', 9 | 'fork', 'plate', 'cup', 'spoon', 'knife'] 10 | 11 | for dish in list(dishwasher): 12 | # check space left in cabinet 13 | if not random.randint(0, 19): 14 | print('Out of space!') 15 | break 16 | else: 17 | print(f'Putting {dish} in the cabinet') 18 | dishwasher.remove(dish) 19 | -------------------------------------------------------------------------------- /examples/10_03_for_break/for_break_end.py: -------------------------------------------------------------------------------- 1 | """ Putting Away Clean Dishes """ 2 | 3 | import random 4 | 5 | # 20 clean dishes in dishwasher 6 | dishwasher = ['plate', 'bowl', 'cup', 'knife', 'fork', 7 | 'spoon', 'plate', 'spoon', 'bowl', 'cup', 8 | 'knife', 'cup', 'cup', 'fork', 'bowl', 9 | 'fork', 'plate', 'cup', 'spoon', 'knife'] 10 | 11 | for dish in list(dishwasher): 12 | # check space left in cabinet 13 | if not random.randint(0, 19): 14 | print('Out of space!') 15 | break 16 | else: 17 | print(f'Putting {dish} in the cabinet') 18 | dishwasher.remove(dish) 19 | -------------------------------------------------------------------------------- /examples/11_01_catch_errors/catch_errors_begin.py: -------------------------------------------------------------------------------- 1 | """ Trying to Download Things That Don't Exist """ 2 | 3 | import urllib.request 4 | 5 | webpage = urllib.request.urlopen('http://www.google.com') 6 | 7 | for line in webpage: 8 | print(line) 9 | -------------------------------------------------------------------------------- /examples/11_01_catch_errors/catch_errors_end.py: -------------------------------------------------------------------------------- 1 | """ Trying to Download Things That Don't Exist """ 2 | 3 | import urllib.request 4 | 5 | try: 6 | webpage = urllib.request.urlopen('http://www.godogle.com') 7 | except: 8 | print('Could not access webpage!') 9 | else: 10 | for line in webpage: 11 | print(line) 12 | -------------------------------------------------------------------------------- /examples/11_02_validate_input/validate_input_begin.py: -------------------------------------------------------------------------------- 1 | """ Overloading a Circuit Breaker """ 2 | 3 | class CircuitBreaker: 4 | def __init__(self, max_amps): 5 | self.capacity = max_amps # max capacity in amps 6 | self.load = 0 # present load in amps 7 | 8 | def connect(self, amps): 9 | self.load += amps 10 | -------------------------------------------------------------------------------- /examples/11_02_validate_input/validate_input_end.py: -------------------------------------------------------------------------------- 1 | """ Overloading a Circuit Breaker """ 2 | 3 | class CircuitBreaker: 4 | def __init__(self, max_amps): 5 | self.capacity = max_amps # max capacity in amps 6 | self.load = 0 # present load in amps 7 | 8 | def connect(self, amps): 9 | if self.load + amps > self.capacity: 10 | raise Exception('Connection will exceed capacity.') 11 | elif self.load + amps < 0: 12 | raise Exception('Connection will cause negative load.') 13 | else: 14 | self.load += amps 15 | 16 | 17 | # Demo Commands (with print() functions to show output when run as main script) 18 | if __name__ == '__main__': 19 | 20 | # create a 20A circuit breaker 21 | cb = CircuitBreaker(20) 22 | print(cb.capacity) 23 | print(cb.load) 24 | 25 | # connect a few devices 26 | cb.connect(12) # vacuum cleaner 27 | cb.connect(7) # stereo 28 | cb.connect(10) # dishwasher 29 | print(cb.load) 30 | 31 | # After making changes: 32 | # 1. exit() current session 33 | # 2. restart Python 34 | # 3. import updated CircuitBreaker class 35 | 36 | # create a new 20A circuit breaker 37 | cb = CircuitBreaker(20) 38 | print(cb.load) 39 | 40 | # connect devices 41 | cb.connect(12) 42 | print(cb.load) 43 | # cb.connect(15) # raises an exception 44 | # cb.connect(-30) # raises an exception 45 | 46 | # After making changes: 47 | # 1. exit() current session 48 | # 2. restart Python 49 | # 3. import updated CircuitBreaker class 50 | 51 | # connect devices 52 | # cb.connect(35) # raises an exception 53 | # cb.connect(-1) # raises an exception 54 | -------------------------------------------------------------------------------- /examples/11_03_custom_errors/custom_errors_begin.py: -------------------------------------------------------------------------------- 1 | """ Handling Household Problems """ 2 | 3 | class ElectricalError(Exception): 4 | def __init__(self, device, problem): 5 | self.device = device 6 | self.problem = problem 7 | 8 | def __str__(self): 9 | return f'The {self.device} is {self.problem}!' 10 | 11 | class PlumbingError(Exception): 12 | def __init__(self, device, problem): 13 | self.device = device 14 | self.problem = problem 15 | 16 | def __str__(self): 17 | return f'The {self.device} is {self.problem}!' 18 | 19 | def cause_error(error_type): 20 | if error_type == 'electrical': 21 | raise ElectricalError('circuit breaker', 'overloaded') 22 | elif error_type == 'plumbing': 23 | raise PlumbingError('dishwasher', 'spraying water') 24 | -------------------------------------------------------------------------------- /examples/11_03_custom_errors/custom_errors_end.py: -------------------------------------------------------------------------------- 1 | """ Handling Household Problems """ 2 | 3 | class ElectricalError(Exception): 4 | def __init__(self, device, problem): 5 | self.device = device 6 | self.problem = problem 7 | 8 | def __str__(self): 9 | return f'The {self.device} is {self.problem}!' 10 | 11 | class PlumbingError(Exception): 12 | def __init__(self, device, problem): 13 | self.device = device 14 | self.problem = problem 15 | 16 | def __str__(self): 17 | return f'The {self.device} is {self.problem}!' 18 | 19 | def cause_error(error_type): 20 | if error_type == 'electrical': 21 | raise ElectricalError('circuit breaker', 'overloaded') 22 | elif error_type == 'plumbing': 23 | raise PlumbingError('dishwasher', 'spraying water') 24 | else: 25 | raise Exception('a generic household problem') 26 | 27 | # cause some problems 28 | try: 29 | cause_error('yard') 30 | except ElectricalError as e: 31 | print(e) 32 | print('Barron fix it.') 33 | except PlumbingError as e: 34 | print(e) 35 | print('Call the plumber.') 36 | except: 37 | print('Call the landlord.') -------------------------------------------------------------------------------- /examples/12_01_polling/front_door.txt: -------------------------------------------------------------------------------- 1 | Welcome Mat 2 | Door Bell -------------------------------------------------------------------------------- /examples/12_01_polling/polling_begin.py: -------------------------------------------------------------------------------- 1 | """ Polling for Pizza to Cure My Hunger """ 2 | 3 | hungry = True # I need a pizza! 4 | 5 | while (hungry): 6 | print('Opening the front door') 7 | front_door = open('front_door.txt', 'r', encoding='utf-8') 8 | 9 | if 'Delivery Person' in front_door: 10 | print('The pizza is here!!!!!!!!!!') 11 | hungry = False 12 | else: 13 | print('Not yet...') 14 | 15 | print('Closing the front door.\n') 16 | front_door.close() 17 | -------------------------------------------------------------------------------- /examples/12_01_polling/polling_end.py: -------------------------------------------------------------------------------- 1 | """ Polling for Pizza Because I'm Hungry! """ 2 | 3 | import time 4 | 5 | hungry = True # I need a pizza! 6 | 7 | while hungry: 8 | print('Opening the front door') 9 | front_door = open('front_door.txt', 'r', encoding='utf-8') 10 | 11 | if 'Delivery Person' in front_door: 12 | print('The pizza is here!!!!!!!!!!') 13 | hungry = False 14 | else: 15 | print('Not yet...') 16 | 17 | print('Closing the front door.\n') 18 | front_door.close() 19 | 20 | time.sleep(1) # rest for 1 second 21 | -------------------------------------------------------------------------------- /examples/12_02_event_driven/event_driven_begin.py: -------------------------------------------------------------------------------- 1 | """ A Brief Study in Handling Life Events """ 2 | 3 | import asyncio 4 | 5 | def alarm(): # handler for when the alarm goes off 6 | print('Wake Up!') 7 | print('Calling the Pizza Company.\n') 8 | loop.call_later(1, alarm) # schedule another alarm 9 | 10 | def doorbell(): # handler for when the doorbell rings 11 | print('Ding! Dong!') 12 | print('Opening the door... "Thanks for bringing the pizza!"\n') 13 | 14 | def phonecall(): # handler for when the phone rings 15 | print('Ring Ring!') 16 | print('Answering the phone... "Hello! Who is this?"\n') 17 | 18 | loop = asyncio.get_event_loop() 19 | loop.call_later(1, alarm) # schedule initial alarm event 20 | loop.call_later(4, doorbell) # schedule doorbell event 21 | loop.call_later(5, phonecall) # schedule phone call event 22 | 23 | print('Starting the event loop...\n') 24 | loop.run_forever() # run until stop() is called 25 | 26 | print('The event loop stopped; closing it down.') 27 | loop.close() 28 | -------------------------------------------------------------------------------- /examples/12_02_event_driven/event_driven_end.py: -------------------------------------------------------------------------------- 1 | """ A Brief Study in Handling Life Events """ 2 | 3 | import asyncio 4 | import time 5 | 6 | def alarm(): # handler for when the alarm goes off 7 | print('Wake Up!') 8 | print('Calling the Pizza Company.\n') 9 | loop.call_later(1, alarm) # schedule another alarm 10 | 11 | def doorbell(): # handler for when the doorbell rings 12 | print('Ding Dong!') 13 | time.sleep(3) 14 | print('Opening the door... "Thanks for bringing the pizza!"\n') 15 | loop.stop() 16 | 17 | def phonecall(): # handler for when the phone rings 18 | print('Ring Ring!') 19 | print('Answering the phone... "Hello! Who is this?"\n') 20 | 21 | loop = asyncio.get_event_loop() 22 | loop.call_later(1, alarm) # schedule initial alarm event 23 | loop.call_later(4, doorbell) # schedule doorbell event 24 | loop.call_later(5, phonecall) # schedule phone call event 25 | 26 | print('Starting the event loop...\n') 27 | loop.run_forever() # run until stop() is called 28 | 29 | print('The event loop stopped; closing it down.') 30 | loop.close() 31 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests>=2.28 2 | --------------------------------------------------------------------------------