├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── pull_request_template.md └── workflows │ ├── lint.yml │ └── stale.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Gemfile ├── LICENSE ├── README.md ├── _config.yml ├── assets ├── Banner1.jpg ├── Banner2.PNG ├── if.png ├── if_elif.png ├── if_else.png ├── iterators.png ├── namespace_memory.png └── nested_if_else.png └── notes ├── chapter-01: The-Language-Basics.md ├── chapter-02: Built-In-func-&-Std-Modules.md ├── exercises ├── ex01_readFile.py ├── ex02_invest.py ├── ex03_caesarCipherV0.py ├── ex04_caesarDecipherV0.py ├── ex05_base10ToBaseX.py ├── ex06_wordsCount.py ├── ex07_newtonSquareRoot.py ├── ex08_median.py ├── ex09_caesarCipherV1.py ├── ex10_caesarDecipherV1.py ├── ex11_caesarCipherV2.py ├── ex12_caesarDecipherv2.py ├── ex13_palindrome.py ├── ex14_cosine_sineAppr.py ├── ex15_pythagoreanTriplets.py ├── ex16_perfectNumbers.py ├── ex17_primes.py ├── ex18_MonteCarlo.py └── ex19_timeModule.py └── projets ├── Project-01: Guess My Number Games ├── computer_guess.py └── player_guess.py ├── Project-02: Word Jumble Game └── jumble_word.py └── Project-03: Tic-Tac-Toe Game └── Tic_Tac_Toe.py /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @wiseaidev 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: "" 5 | labels: "" 6 | assignees: "" 7 | --- 8 | 9 | **Describe the bug** 10 | A clear and concise description of what the bug is. 11 | 12 | **To Reproduce** 13 | Steps to reproduce the behavior: 14 | 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | 28 | - OS: [e.g. iOS] 29 | - Browser [e.g. chrome, safari] 30 | - Version [e.g. 22] 31 | 32 | **Smartphone (please complete the following information):** 33 | 34 | - Device: [e.g. iPhone6] 35 | - OS: [e.g. iOS8.1] 36 | - Browser [e.g. stock browser, safari] 37 | - Version [e.g. 22] 38 | 39 | **Additional context** 40 | Add any other context about the problem here. 41 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "" 5 | labels: "" 6 | assignees: "" 7 | --- 8 | 9 | **Is your feature request related to a problem? Please describe.** 10 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 11 | 12 | **Describe the solution you'd like** 13 | A clear and concise description of what you want to happen. 14 | 15 | **Describe alternatives you've considered** 16 | A clear and concise description of any alternative solutions or features you've considered. 17 | 18 | **Additional context** 19 | Add any other context or screenshots about the feature request here. 20 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | ### What was wrong? 2 | 3 | Related to Issue # 4 | 5 | ### How was it fixed? 6 | 7 | #### Cute Animal Picture 8 | 9 | :dog: 10 | -------------------------------------------------------------------------------- /.github/workflows/lint.yml: -------------------------------------------------------------------------------- 1 | name: Lint Awesome List 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: 7 | - main 8 | 9 | jobs: 10 | lint: 11 | name: Lint 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v1.0.0 15 | - uses: max/awesome-lint@v2.0.0 16 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Mark stale issues and pull requests 2 | 3 | on: 4 | schedule: 5 | - cron: "0 0 * * *" 6 | 7 | jobs: 8 | stale: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | - uses: actions/stale@v1 14 | with: 15 | repo-token: ${{ secrets.GITHUB_TOKEN }} 16 | stale-issue-message: 'This issue is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 14 days' 17 | stale-pr-message: 'This PR is stale because it has been open 90 days with no activity. Remove stale label or comment or this will be closed in 14 days' 18 | stale-issue-label: 'no-issue-activity' 19 | stale-pr-label: 'no-pr-activity' 20 | days-before-stale: 90 21 | days-before-close: 14 22 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | [our gitter channel][01]. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | 130 | [01]: https://gitter.im/awesome-pycon/community 131 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # 📝 Contribution Guidline 2 | 3 | Contributions are welcome, and they are greatly appreciated! Every little bit helps, and a credit will always be given. 4 | 5 | ## Agreement 6 | 7 | By submitting fixes to this project you agree to allow them to be redistributed under the MIT license, according to the normal forms and usages of the open-source community. 8 | 9 | ## Introduction 10 | 11 | First thing first, I would like to thank you for considering this project. It's people like you that make it such a wonderful place. 12 | 13 | Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open-source project. In return, they should reciprocate that respect in addressing your issue, assessing changes, and helping you finalize your pull requests. 14 | 15 | This is an open-source project and we love to receive contributions from our community; yes you! There are many ways to contribute, from sharing your python notes, submitting bug reports and feature requests, or writing code that can be incorporated into the main project itself. 16 | 17 | ### I don't want to read this whole thing I just have a question!!! 18 | 19 | We are using a [gitter channel][01] for support questions. But please be wary that maintaining an open-source project can take a lot of time from the maintainers. If asking for a support question, state it clearly and take the time to explain your problem properly. Also, if your problem is not strictly related to this project, we recommend you to use Stack Overflow instead. 20 | 21 | ## How Can I Contribute? 22 | 23 | You can contribute in many ways: 24 | 25 | ### Types of Contributions 26 | 27 | #### Report Bugs 28 | 29 | Report bugs at [awesome-python/issues][02]. 30 | 31 | If you are reporting a bug, please include: 32 | 33 | - Your operating system name and version. 34 | - Any details about your local setup that might be helpful in troubleshooting. 35 | - Detailed steps to reproduce the bug. 36 | 37 | #### Fix Bugs 38 | 39 | Look through the GitHub issues for bugs. Anything tagged with "bug" and "help 40 | wanted" is open to whoever wants to implement it. 41 | 42 | #### Implement Features 43 | 44 | Look through the GitHub issues for features. Anything tagged with "enhancement" 45 | and "help wanted" is open to whoever wants to implement it. 46 | 47 | #### Share your Notes 48 | 49 | This project could always use more notes, whether as part of the official 50 | awesome-python, in blog posts, articles, and such. 51 | 52 | #### Submit Feedback 53 | 54 | The best way to send feedback is to ask a question at [our Gitter channel][01]. 55 | 56 | If you are willing to share notes: 57 | 58 | - Add your notes under the notes folder. 59 | - Remember that this is a volunteer-driven project and that contributions are welcome :) 60 | 61 | ### Get Started! 62 | 63 | Ready to contribute? Here's how to share your notes and fixes. 64 | 65 | 1. Fork the `awesome-python` repo on GitHub. 66 | 2. Clone your fork locally: 67 | 68 | ```bash 69 | $ git clone git@github.com:your_username_here/awesome-python.git 70 | ``` 71 | 72 | 3. Create a branch for adding your notes: 73 | 74 | ```bash 75 | $ git checkout -b name-it-whatever-you-want 76 | ``` 77 | 78 | #### Submitting Notes: 79 | 80 | Please ensure your pull request adheres to the following guidelines: 81 | 82 | - Search previous suggestions before making a new one, as yours may be a duplicate. 83 | - Make an individual pull request for each suggestion. 84 | - Place your note file under the notes folder. 85 | - Link it in the readme file. 86 | 87 | #### Submitting PyCon Videos: 88 | 89 | Please ensure your pull request adheres to the following guidelines: 90 | 91 | - Search previous suggestions before making a new one, as yours may be a duplicate. 92 | - Make an individual pull request for each suggestion. 93 | - Use the following format: 94 | 95 | ```html 96 | | Thumbnail | Video 97 | Title | 98 | [`videos_timestamps_year`][unique_numbre] | `Video Duration` | [`Speaker Slides 99 | Deck`][unique_numbre] | [`Cloud_Provider_link_backup`][unique_numbre] | 100 | ``` 101 | 102 | - Link each of the corresponding links at the bottom of the page: 103 | 104 | ```html 105 | 106 | [unique_numbre]: URL 107 | ``` 108 | 109 | - Check your spelling and grammar. 110 | 111 | #### Suggesting a book. 112 | 113 | - Search previous suggestions before making a new one, as yours may be a duplicate. 114 | - Make an individual pull request for each suggestion. 115 | - Use the following format: 116 | 117 | ```html 118 | | Book Cover | Book title, Edition. 119 | | Author | `year of publication` | 120 | [`Publisher`][unique_numbre] | [`Store`][unique_numbre] | 121 | ``` 122 | 123 | - Link each of the corresponding links at the bottom of the page: 124 | 125 | ```html 126 | 127 | [unique_numbre]: URL 128 | ``` 129 | 130 | ### Commit and push your changes! 131 | 132 | 1. Commit your changes and push your branch to GitHub:: 133 | 134 | ```bash 135 | $ git add . 136 | $ git commit -m "Your detailed description of your changes." 137 | $ git push origin name-of-your-note-branch 138 | ``` 139 | 140 | 2. Submit a pull request through the GitHub website. 141 | 142 | - Make sure that the pull request has a meaningful title. 143 | 144 | Thank you for helping us improve!!! 145 | 146 | 147 | 148 | [01]: https://gitter.im/awesome-pycon/community 149 | [02]: https://github.com/Harmouch101/awesome-python/issues 150 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | gem 'jekyll-relative-links' 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020-2022 Mahmoud Harmouch 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 6 | # Awesome Python [![Awesome](https://awesome.re/badge-flat.svg)](https://github.com/sindresorhus/awesome) 7 | 8 |
9 | 10 | Join the chat at https://gitter.im/awesome-pycon/community 11 | 12 | 13 | Open Source Love 14 | 15 | 16 | License 17 | 18 | 19 | Code of Conduct 20 | 21 | 22 | Repo Size 23 | 24 |
25 | 26 | 28 | 29 | 32 | 33 |
34 | 35 | Awesome Python 36 | 37 |
38 |
39 | 40 | --- 41 | 42 | ## 📜 Summary 43 | 44 | A curated list of python tutorials, notes, slides deck, files related to pycon talks, and a handful list of books that are worth reading. This repository can be used as a reference documentation for mastering the python programming language and other related content like frameworks and such. 45 | 46 | This repository serves three primary roles: 47 | 48 | 1. Sharing an opinionated list of python videos. 49 | 50 | 2. Sharing notes driven by the awesome community. 51 | 52 | 3. Sharing a handful list of books that can play a significant role in honing your python skills. 53 | 54 | 55 | > If you are looking for a way to contribute to the project, please refer to the [`Guideline`][00]. 56 | 57 | > Don't forget to slap that ⭐ button an odd number of times ;-) 58 | 59 | > Currently maintained by [`Mahmoud Harmouch`][01]. 60 | 61 | --- 62 | ## 👉 Table Of Content (TOC). 63 | 64 | 1. [Python Talks](#Talks) 65 | 1.1. [Novice Level - Core](#Novice) 66 | 1.2. [Intermediate Level - Core](#Intermediate) 67 | 1.3. [Generic](#generic) 68 | 1.4. [Python 2 and Python 3](#2to3) 69 | 1.5. [DSA](#DSA) 70 | 1.6. [DevOps](#DevOps) 71 | 1.7. [Full-Stack](#Full) 72 | 1.8. [Self Care & Life](#SelfCare) 73 | 1.9. [Testing](#Testing) 74 | 1.10. [Refactoring](#refactoring) 75 | 1.11. [ML & Statistics](#ml-statistics) 76 | 1.12. [Security](#security) 77 | 1.13. [Async Programming](#async-programming) 78 | 79 | 2. [Notes by the community](#notes) 80 | 2.1. [Chapter-01: The Language Basics](#chapter1) 81 | 2.2. [Chapter-02: Built-In functions and the Std-Modules](#chapter2) 82 | 83 | 3. [Python Books](#books) 84 | 3.1. [Novice Level](#books3.1) 85 | 3.2. [Intermediate Level](#books3.2) 86 | 3.3. [Reference](#books3.3) 87 | --- 88 | 89 | ## 1. 📺 Python Talks 90 | 91 | #### 🔝 [Go To TOC](#TOC). 92 | 93 | ### 1.1 Novice Level 94 | 95 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 96 | | :---:| :---: | :------------: | :------------: | :------------: | :------------: | 97 | | | Python Epiphanies | [`2014`][000] [`2016`][001] [`2017`][002] [`2018`][003] | `3:17:08` | [`2015`][0000] [`2016`][0001] [`2018`][0002] | [`Mega`][00000] | 98 | | | Hands-On Intro to Python | [`2017`][010] | `3:26:03` | [`2017`][0100]| --- | 99 | | | Hands-on Intro to Python For Beginning Programmers | [`2014`][020] | `3:21:49` | --- | --- | 100 | 101 | --- 102 | 103 | ### 1.2 Intermediate Level 104 | 105 | #### 🔝 [Go To TOC](#TOC). 106 | 107 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 108 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 109 | | | Pythonic Objects | [`2019`][110] | `3:22:15` | [`2014`][1100] [`Github`][1101] | [`Mega`][11000] | 110 | | | Pythonic APIs | [`2016`][120] | `3:01:52` | [`2016`][1200] [`Github`][1201] | [`Mega`][12000] | 111 | | | Decorators & Descriptors | [`2017`][130] | `2:55:02` | [`2017`][1300] | [`Mega`][13000] | 112 | | | Lazy Looping in Python | [`2019`][140] | `3:22:14` | [`2017`][1400] | --- | 113 | | | List Comprehensions & Generators | [`2018`][150] | `3:21:43` | [`2017`][1500] | --- | 114 | | | Readable Regular Expressions | [`2016`][160] [`2017`][161] [`2021`][162] | `3:19:43` | [`2016`][1600] [`2017`][1601] [`2021`][1602] | --- | 115 | | | Dataclasses: The code generator to end all code generators | [`2018`][170] | `00:45:21` | --- | --- | 116 | | | Object Oriented Programming from scratch | [`2020`][180] | `1:16:18` | [`Colab`][1800] | --- | 117 | | | Design Patterns in Python for the Untrained Eye | [`2019`][190] | `3:14:47` | [`2019`][1900] | --- | 118 | 119 | --- 120 | 121 | ### 1.3 Generic 122 | 123 | #### 🔝 [Go To TOC](#TOC). 124 | 125 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 126 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 127 | | | Discovering Python | [`2014`][210] | `00:47:49` | [`2014`][2100] |[`Mega`][21000] | 128 | | | The Fun of Reinvention | [`2017 - Screencast`][220] [`2017`][221] | `00:55:21` | [`2017`][2200] |[`Mega`][22000] | 129 | | | Fear and Awaiting in Async | [`2016 - Screencast`][230] [`2016`][231] | `00:56:42` | [`2016`][2300] | [`Mega`][23000] | 130 | | | Built in Super Heroes | [`2016 - Screencast`][240] [`2016`][241] | `00:44:31` | [`2016`][2400] | [`Mega`][24000] | 131 | 132 | --- 133 | 134 | ### 1.4 Python 2 and Python 3 135 | 136 | #### 🔝 [Go To TOC](#TOC). 137 | 138 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 139 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 140 | | | Python 3.3 is better Than Python 2.7 | [`2012`][310] [`2013`][311] | `00:53:24` | [`2013`][3100] | --- | 141 | | | How to make your code Python 2/3 compatible | [`2015`][320] | `00:28:37` | [`2015`][3200] | --- | 142 | 143 | --- 144 | 145 | ### 1.5 Data Structures & Algorithms 146 | 147 | #### 🔝 [Go To TOC](#TOC). 148 | 149 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 150 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 151 | | | Data Structures in the Std Lib and Beyond | [`2014`][410] | `00:37:40` | [`2014`][4100] | --- | 152 | | | Computer science fundamentals | [`2014`][420] | `00:30:22` | [`2014`][4200] | --- | 153 | | | Modern solvers: Problems well-defined are problems solved(BFS, DFS) | [`2019`][430] | `00:47:14` | [`2019`][4300] | --- | 154 | | | Build powerful, new data structures with Python's abstract base classes | [`2019`][440] | `1:02:01` | --- | --- | 155 | | | Efficient shared memory data structures | [`2018`][450] | `00:27:15` | [`2018`][4500] | --- | 156 | | | Learning Algorithms and Data Structures in Python | [`2012`][460] | `00:34:43` | --- | --- | 157 | | | Elegant Solutions For Everyday Python Problems | [`2018`][470] | `00:32:57` | [`2018`][4700] | --- | 158 | | | Fuzzy Search Algorithms How and When to Use Them | [`2017`][480] | `00:30:23` | [`2017`][4800] | --- | 159 | 160 | --- 161 | 162 | ### 1.6 DevOps 163 | 164 | #### 🔝 [Go To TOC](#TOC). 165 | 166 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 167 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 168 | | | Beyond grep: Practical Logging and Metrics | [`2015`][510] | `00:35:50` | [`2015`][5100] | --- | 169 | 170 | --- 171 | 172 | ### 1.7 Full-Stack 173 | 174 | #### 🔝 [Go To TOC](#TOC). 175 | 176 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 177 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 178 | | | So you want to be a full-stack developer | [`2014`][610] | `00:26:46` | [`2014`][6100] | --- | 179 | | | Building full-stack scientific applications in Python | [`2013`][620] | `00:42:35` | [`2013`][6200] [`gist`][6201]| --- | 180 | | | To ORM or not to ORM | [`2015`][630] | `00:26:29` | [`2015`][6300]| --- | 181 | | | Flask | [`2014`][640] [`2015`][641] [`2016`][642] [`2017`][642] | `3:40:28` | [`2014`][6400] [`2015`][6401] [`2016`][6402] [`2017`][6403] | --- | 182 | | | the Django Request-Response Cycle | [`2014`][650] | `00:31:27` | [`2014`][6500]| --- | 183 | | | Designing Django's Migrations | [`2014`][660] | `00:26:26` | [`2014`][6600]| --- | 184 | | | API-Driven Django | [`2018`][670] | `00:26:26` | [`2014`][6700]| --- | 185 | | | Beyond Django Basics | [`2018`][680] | `3:15:59` | [`Github`][6800]| --- | 186 | | | Django Admin Basics and Beyond | [`2017`][6100] | `3:13:21` | [`Github`][61000]| --- | 187 | | | Getting Started with Django | [`2014`][6110] | `3:23:34` | [`RTD`][61100]| --- | 188 | | | Django 101 | [`2016`][6120] | `2:04:32` | [`2016`][61200] [`Github`][61201] | --- | 189 | | | PostgreSQL Proficiency for Python People | [`2016`][6130] | `3:00:05` | [`pdf`][61300]| --- | 190 | | | Delving into the Django Admin | [`2015`][6140] | `3:05:24` | [`Github`][61400]| --- | 191 | | | SQLAlchemy 2.0 - The One-Point-Four-Ening 2021 | [`2021`][6150] [`2013`][6151] [`2013`][6152]| `2:44:38` | [`Github`][61500] [`2013`][61501] [`2013`][61502]| --- | 192 | | | FastAPI from the ground up | [`2019`][6160] | `00:26:33` | [`Github`][61600] | --- | 193 | | | FastAPI - The most modern Python3 web framework | [`2021`][6170] | `00:26:33` | --- | --- | 194 | | | FastAPI Seems Good, so Why Don't We Build Something Similar For Flask? | [`2021`][6180] | `00:04:44` | [`slides`][61800] | --- | 195 | 196 | --- 197 | 198 | ### 1.8 Self Care & Life 199 | 200 | #### 🔝 [Go To TOC](#TOC). 201 | 202 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 203 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 204 | | | It's Dangerous to Go Alone | [`2014`][710] | `00:28:22` | [`2014`][7100] | --- | 205 | | | Technical on-boarding, training, and mentoring | [`2014`][720] | `00:27:11` | [`2014`][7200] | --- | 206 | | | Avoiding Burnout, and other essentials of Open Source Self-Care | [`2015`][730] | `00:28:35` | [`2015`][7300] | --- | 207 | | | Why can't we be friends: do corporations and FOSS really mix? | [`2016`][740] | `00:31:26` | [`2016`][7400] | --- | 208 | | | The Journey Over the Intermediate Gap | [`2018`][750] | `00:27:09` | [`2018`][7500] | --- | 209 | | | Build Teams as an Engineer | [`2018`][760] | `00:31:55` | [`2018`][7600] | --- | 210 | | | Does remote work really work | [`2019`][770] | `00:39:20` | [`2019`][7700] | --- | 211 | 212 | --- 213 | 214 | ### 1.9 Testing 215 | 216 | #### 🔝 [Go To TOC](#TOC). 217 | 218 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 219 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 220 | | | TDD with Django | [`2018`][810] [`2018`][811] [`2017`][812] | `3:11:52` | [`Book`][8100] [`Github`][8101] | --- | 221 | | | Visual Testing with PyCharm and pytest | [`2018`][820] | `00:29:54` | [`2018`][8200] | --- | 222 | | | Beyond Unit Tests: Taking Your Testing to the Next Level | [`2018`][830] | `00:29:20` | [`2018`][8300] | --- | 223 | | | Escape from auto-manual testing with Hypothesis! | [`2019`][840] | `3:12:11` | [`2019`][8400] | --- | 224 | | | Getting Started Testing in Data Science | [`2019`][850] | `00:31:00` | [`2019`][8500] | --- | 225 | | | Strategies for testing Async code | [`2019`][860] | `00:22:43` | [`2019`][8600] | --- | 226 | 227 | --- 228 | 229 | ### 1.10 Refactoring 230 | 231 | #### 🔝 [Go To TOC](#TOC). 232 | 233 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 234 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 235 | | | The Refactoring Balance Beam: When to Make Changes and When to Leave it Alone | [`2019`][910] | `00:28:23` | [`2019`][9100] | --- | 236 | | | Refactoring Python: Why and how to restructure your code | [`2016`][920] | `00:30:24` | [`2016`][9200] | --- | 237 | | | Beautiful Python Refactoring | [`2020`][930] | `00:30:04` | --- | --- | 238 | | | Refactoring in Python: Design Patterns and Approaches | [`2019`][940] [`2018`][941] | `00:46:56` | [`2018`][9400] | --- | 239 | | | Dr. Kristian Rother - Best Practices | [`2022`][950] [`2017`][951] | `01:29:49` | [`Github`][9500] | --- | 240 | 241 | --- 242 | 243 | ### 1.11 ML & Statistics 244 | 245 | #### 🔝 [Go To TOC](#TOC). 246 | 247 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 248 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 249 | | | Bayesian Statistics Made Simple. | [`2019`][1010] [`2016`][1011] [`2015`][1012] [`2014`][1013] [`2013`][1014]| `02:19:12` | [`G-Docs`][10100] [`Github Pages`][10101] [`Github Repo`][10102] [`Notebook`][10103] [`SpeakerDeck`][10104]| --- | 250 | 251 | --- 252 | 253 | ### 1.12 Security 254 | 255 | #### 🔝 [Go To TOC](#TOC). 256 | 257 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 258 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 259 | | | Practical API Security. | [`2019`][1110] [`2018`][1111] | `03:18:36` | [`Github`][11100] | --- | 260 | | | An introduction to secure web development with Django and Python. | [`2017`][1120] | `02:56:15` | --- | --- | 261 | 262 | --- 263 | 264 | ### 1.13 Async Programming 265 | 266 | #### 🔝 [Go To TOC](#TOC). 267 | 268 | | Thumbnail | Video Title | YT Links | Duration | Speaker Deck | Backup files | 269 | | :---: | :---: | :------------: | :------------: | :------------: | :------------: | 270 | | | Asynchronous Python for the Complete Beginner. | [`2017`][1210] | `00:30:57` | [`Gist`][12100] [`2017`][12101] | --- | 271 | | | Asynchronous Web Development with Flask. | [`2019`][1220] | `00:27:21` | [`2019`][12200] | --- | 272 | | | Get to grips with asyncio in Python 3. | [`2017`][1230] | `00:59:22` | --- | --- | 273 | 274 | --- 275 | 276 | ## 2. 📝 Notes by the community. 277 | 278 | #### 🔝 [Go To TOC](#TOC). 279 | 280 | ### [Chapter-01: The Language Basics][0]. 281 | 282 | ### [Chapter-02: Built-In functions and the Std-Modules][1]. 283 | 284 | --- 285 | 286 | ## 3. 📚 Python Books(Core). 287 | 288 | #### 🔝 [Go To TOC](#TOC). 289 | 290 | ### 3.1 Novice Level. 291 | 292 | | Cover | Title | Authors | Publication(Year) | Publisher | Store | 293 | | :----: | :----: | :----: | :----: | :----: | :----: | 294 | | | Head-First Python, 2nd Edition. | Paul Barry | `2016` | [`O'Reilly Media, Inc`][3.1.1] | [`Amazon`][3.1.1.1] | 295 | | | Python for Everybody. | Dr. Charles Russell Severance. | `2017` | [`O'Reilly`][3.1.2] | [`Amazon`][3.1.2.1] | 296 | | | Learn Python 3 the Hard Way, 1st Edition. | Zed A. Shaw | `2017` | [`Addison-Wesley`][3.1.3] | [`Amazon`][3.1.3.1] | 297 | | | Python Programming for the Absolute Beginner, 3rd Edition. | Michael Dawson | `2010` | Course Technology | [`Amazon`][3.1.4.1] | 298 | | | Introduction to Computation and Programming Using Python, 2nd Edition. | John V. Guttag, Julie Sussman | `2016` | [`The MIT Press`][3.1.5] | [`Amazon`][3.1.5.1] | 299 | | | Python Programming: An Introduction to Computer Science, 3rd Edition. | John M. Zelle | `2016` | Franklin, Beedle & Associates, Inc | [`Amazon`][3.1.6.1] | 300 | | | Python Crash Course, 2nd Edition. | Eric Matthes | `2019` | [`No Starch Press`][3.1.7] | [`Amazon`][3.1.7.1] | 301 | | | Python for Kids, 2nd Edition. | Jason R. Briggs | `2012` | [`No Starch Press`][3.1.8] | [`Amazon`][3.1.8.1] | 302 | | | Core Python Programming, 2nd Edition | Wesley J. Chun | `2006` | [`Pearson P T R`][3.1.9] | [`Amazon`][3.1.9.1] | 303 | | | Programming Python, 4th Edition | Mark Lutz | `2010` | [`O'Reilly Media, Inc.`][3.1.10] | [`Amazon`][3.1.10.1] | 304 | | | Learning Python, 5th Edition. | Mark Lutz | `2010` | [`O'Reilly Media, Inc.`][3.1.11] | [`Amazon`][3.1.11.1] | 305 | | | Think Python, 2nd Edition. | Allen B. Downey | `2016` | [`O'Reilly Media, Inc.`][3.1.12] | [`Amazon`][3.1.12.1] | 306 | 307 | --- 308 | 309 | ## 3.2 Intermediate Level 310 | 311 | #### 🔝 [Go To TOC](#TOC). 312 | 313 | | Cover | Title | Authors | Publication(Year) | Publisher | Store | 314 | | :----: | :----: | :----: | :----: | :----: | :----: | 315 | | | Murach's Python Programming, 2nd Edition. | Michael Urban | `2021` | [`Mike Murach & Associates`][3.2.1] | [`Amazon`][3.2.1.1] | 316 | | | Python Distilled (Developer's Library) 1st Edition. | David Beazley | `2021` | [`Addison-Wesley Professional`][3.2.2] | [`Amazon`][3.2.1.2] | 317 | | | Effective Python, 2nd Edition. | Brett Slatkin | `2019` | [`Addison-Wesley Professional`][3.2.3] | [`Amazon`][3.2.1.3] | 318 | | | Python Tricks, 1st edition. | Dan Bader | `2017` | [`Dan Bader`][3.2.4] | [`Amazon`][3.2.1.4] | 319 | | | Intermediate Python, 1st edition. | Obi Ike-Nwosu | `2016` | [`leanpub`][3.2.5] | --- | 320 | | | Python Object-Oriented Programming, 4th Edition. | Steven F. Lott, Dusty Phillips | `2021` | [`Packt Publishing`][3.2.6] | [`Amazon`][3.2.1.6] | 321 | | | Problem Solving with Algorithms and Data Structures Using Python, Kindle Edition. | Bradley N. Miller, David L. Ranum | `2021` | [`Franklin, Beedle & Associates`][3.2.7] | [`Amazon`][3.2.1.7] | 322 | | | Practices of the Python Pro 1st Edition. | Dane Hillard | `2020` | [`Manning`][3.2.8] | [`Amazon`][3.2.1.8] | 323 | 324 | --- 325 | 326 | ## 3.3 Reference 327 | 328 | 329 | #### 🔝 [Go To TOC](#TOC). 330 | 331 | | Cover | Title | Authors | Publication(Year) | Publisher | Store | 332 | | :----: | :----: | :----: | :----: | :----: | :----: | 333 | | | Fluent Python, 2nd Edition. | Luciano Ramalho | `2022` | [`O'Reilly Media`][3.3.1] | [`Amazon`][3.3.1.1] | 334 | | | Mastering Python High Performance. | Fernando Doglio | `2015` | [`Packt Publishing`][3.3.2] | [`Amazon`][3.3.2.1] | 335 | | | Python Testing with pytest, 2nd Edition | Brian Okken | `2022` | [`Pragmatic Bookshelf`][3.3.3] | [`Amazon`][3.3.3.1] | 336 | 337 | --- 338 | 339 | #### 🔝 [Go To TOC](#TOC). 340 | 341 |

342 | © 2022 Mahmoud Harmouch, all rights reserved. Made with ❤️
343 | Contributions are welcome! 344 |

345 | 346 | 347 | 348 | [0]: https://wiseaidev.github.io/awesome-python/notes/chapter-01:%20The-Language-Basics.html 349 | [1]: https://wiseaidev.github.io/awesome-python/notes/chapter-02:%20Built-In-func-&-Std-Modules.html 350 | 351 | [00]: https://wiseaidev.github.io/awesome-python/CONTRIBUTING.html 352 | [01]: https://github.com/wiseaidev 353 | 354 | [010]: https://www.youtube.com/watch?v=6zu8lrYn6t8 355 | [0100]: https://intro2017.trey.io/ 356 | 357 | [000]: https://www.youtube.com/watch?v=Uyj2UFTL_vg 358 | [001]: https://www.youtube.com/watch?v=6inqFd1bUkE 359 | [002]: https://www.youtube.com/watch?v=oQca6eDcjA8 360 | [003]: https://www.youtube.com/watch?v=-kqZtZj4Ky0&t=840s 361 | [0000]: https://www.dropbox.com/s/az1gnn92u8y6eh3/PyCon%202015%20-%20Python%20Epiphanies.pdf?dl=0 362 | [0001]: https://www.dropbox.com/s/dgks2bgnzpycruz/PyCon-2016-Python-Epiphanies.zip?dl=0 363 | [0002]: https://www.dropbox.com/s/xkyk3sgbq5fwdzh/PyCon-2018-Python-Epiphanies.zip?dl=0 364 | [00000]: https://mega.nz/folder/XP4XCIiB#KEex7dWMu6FLAcIOH09H_g 365 | 366 | [110]: https://www.youtube.com/watch?v=mUu_4k6a5-I 367 | [1100]: https://speakerdeck.com/ramalho/idiomatic-apis-with-the-python-data-model 368 | [1101]: https://github.com/ramalho/pyob 369 | [11000]: https://mega.nz/file/2XwGiaqB#jL8M3xrlnAYwwFgRvwXZJThi_B_pn-2n3-r-0hmvyWk 370 | 371 | [120]: https://www.youtube.com/watch?v=k55d3ZUF3ZQ 372 | [1200]: https://speakerdeck.com/ramalho/pythonic-apis-1 373 | [1201]: https://github.com/fluentpython/example-code 374 | [12000]: https://mega.nz/file/LG5gBC6I#LSU06PQHH_893orecD_PZfeTmX9jaT8uyhSBZ-3daoU 375 | 376 | [130]: https://www.youtube.com/watch?v=81S01c9zytE 377 | [1300]: https://speakerdeck.com/ramalho/decorators-decoded 378 | [13000]: https://mega.nz/file/DfgATCrS#xM4ss0XtUbw86iJTY4yrujC8mrLhyZUE5wtpcl74VQE 379 | 380 | [140]: https://www.youtube.com/watch?v=ixiRkUwPI2A 381 | [1400]: https://pycon2019.trey.io/ 382 | 383 | [150]: https://www.youtube.com/watch?v=_6U1XoxyyBY 384 | [1500]: https://pycon2018.trey.io/ 385 | 386 | [160]: https://www.youtube.com/watch?v=W4ReH9IPH-Q 387 | [1600]: https://pycon2016.regex.training/ 388 | 389 | [161]: https://www.youtube.com/watch?v=0sOfhhduqks 390 | [1601]: https://pycon2017.regex.training/ 391 | 392 | [162]: https://www.youtube.com/watch?v=aTZalKdYB44 393 | [1602]: https://pycon2021.regex.training/ 394 | 395 | [170]: https://www.youtube.com/watch?v=T-TwcmT6Rcw 396 | 397 | [180]: https://www.youtube.com/watch?v=8moWQ1561FY 398 | [1800]: https://colab.research.google.com/drive/1DoRrfo839lT_nqmLU6cVLdZJV9wCR2BW?usp=sharing#scrollTo=bYulP3G2XFwJ 399 | 400 | [190]: https://www.youtube.com/watch?v=o1FZ_Bd4DSM 401 | [1900]: https://arielortiz.info/s201911/pycon2019/docs/design_patterns.html 402 | 403 | [210]: https://www.youtube.com/watch?v=RZ4Sn-Y7AP8 404 | [2100]: https://speakerdeck.com/pycon2014/discovering-python-by-david-beazley 405 | [21000]: https://mega.nz/file/PWxQiCBZ#bEm7uY_JkPz4kxVYgoSlVdaoMKFOtzgpEDRK3L7HHvk 406 | 407 | [220]: https://www.youtube.com/watch?v=js_0wjzuMfc 408 | [221]: https://www.youtube.com/watch?v=5nXmq1PsoJ0 409 | [2200]: https://speakerdeck.com/dabeaz/the-fun-of-reinvention 410 | [22000]: https://mega.nz/file/nLwkGaKT#o0e1aVV98PbOJx1h2BP7gEC77M7p-1coKua4LB3pTW8 411 | 412 | [230]: https://www.youtube.com/watch?v=Bm96RqNGbGo 413 | [231]: https://www.youtube.com/watch?v=E-1Y4kSsAFc 414 | [2300]: https://speakerdeck.com/dabeaz/fear-and-awaiting-in-async-a-savage-journey-to-the-heart-of-the-coroutine-dream 415 | [23000]: https://mega.nz/file/yTgSzIoY#R3VR6lLAj8RJ7jugMy6PDPoq-3N1L4j-4RUG9d6vBmo 416 | 417 | [240]: https://www.youtube.com/watch?v=j6VSAsKAj98 418 | [241]: https://www.youtube.com/watch?v=lyDLAutA88s 419 | [2400]: https://speakerdeck.com/dabeaz/builtin-superheroes 420 | [24000]: https://mega.nz/file/uf5mWYQK#6k0-a2VKMyfBvA5viWggASC-6Apgehvoh13aDYb3vLM 421 | 422 | [020]: https://www.youtube.com/watch?v=MirG-vJOg04 423 | 424 | [310]: https://www.youtube.com/watch?v=Ebyz66jPyJg 425 | [311]: https://www.youtube.com/watch?v=f_6vDi7ywuA 426 | [3100]: https://speakerdeck.com/pyconslides/python-3-dot-3-trust-me-its-better-than-python-2-dot-7-by-dr-brett-cannon 427 | 428 | [320]: https://www.youtube.com/watch?v=KPzDX5TX5HE 429 | [3200]: https://speakerdeck.com/pycon2015/3-compatible 430 | 431 | [410]: https://youtu.be/fYlnfvKVDoM?t=330 432 | [4100]: https://rhodesmill.org/brandon/slides/2014-04-pycon/data-structures/ 433 | 434 | [420]: https://www.youtube.com/watch?v=nEquiifH33w 435 | [4200]: https://speakerdeck.com/pycon2014/computer-science-fundamentals-for-self-taught-programmers-by-justin-abrahms 436 | 437 | [430]: https://www.youtube.com/watch?v=_GP9OpZPUYc 438 | [4300]: https://rhettinger.github.io/ 439 | 440 | [440]: https://www.youtube.com/watch?v=S_ipdVNSFlo 441 | 442 | [450]: https://www.youtube.com/watch?v=52zM4GgmqDE 443 | [4500]: https://speakerdeck.com/pycon2018/claudio-freire-efficient-shared-memory-data-structures 444 | 445 | [460]: https://www.youtube.com/watch?v=HN5-7Kn_XsI 446 | 447 | [470]: https://www.youtube.com/watch?v=WiQqqB9MlkA 448 | [4700]: https://www.slideshare.net/nnja/elegant-solutions-for-everyday-python-problems-pycon-2018 449 | 450 | [480]: https://www.youtube.com/watch?v=kTS2b6pGElE 451 | [4800]: https://github.com/itsJiaqi/fuzzy-search-talk 452 | 453 | [510]: https://www.youtube.com/watch?v=LklGF1rcJII 454 | [5100]: https://speakerdeck.com/pycon2015/hynek-schlawack-beyond-grep-practical-logging-and-metrics 455 | 456 | [610]: https://www.youtube.com/watch?v=8uxQOzKi3_0 457 | [6100]: https://speakerdeck.com/pycon2014/so-you-want-to-be-a-full-stack-developer-how-to-build-a-full-stack-python-web-application-by-kate-heddleston 458 | 459 | [620]: https://www.youtube.com/watch?v=Znj3fovTSfk 460 | [6200]: https://durden.github.io/python_science_apps/#1 461 | [6201]: https://gist.github.com/durden/5113132 462 | 463 | [630]: https://www.youtube.com/watch?v=Sadng6tR7Q4 464 | [6300]: https://speakerdeck.com/pycon2015/christine-spang-to-orm-or-not-to-orm 465 | 466 | [640]: https://www.youtube.com/watch?v=FGrIyBDQLPg 467 | [641]: https://www.youtube.com/watch?v=DIcpEg77gdE 468 | [642]: https://www.youtube.com/watch?v=tdIIJuPh3SI 469 | [643]: https://www.youtube.com/watch?v=nrzLdMWTRMM 470 | [6400]: https://speakerdeck.com/miguelgrinberg/flask-by-example-pycon-2014 471 | [6401]: https://speakerdeck.com/miguelgrinberg/flask-workshop-pycon-2015 472 | [6402]: https://speakerdeck.com/miguelgrinberg/flask-at-scale 473 | [6403]: https://speakerdeck.com/miguelgrinberg/microservices-with-python-and-flask 474 | 475 | [650]: https://www.youtube.com/watch?v=q0YqAbI7rw4 476 | [6500]: https://speakerdeck.com/pycon2014/a-scenic-drive-through-the-django-request-response-cycle-by-dan-langer 477 | 478 | [660]: https://www.youtube.com/watch?v=a-_GAHfpk1Y 479 | [6600]: https://speakerdeck.com/pycon2014/designing-djangos-migrations-by-andrew-godwin 480 | 481 | [670]: https://www.youtube.com/watch?v=w0xgJ5C9Be8 482 | [6700]: https://speakerdeck.com/phildini/api-driven-django 483 | 484 | [680]: https://www.youtube.com/watch?v=Fzlg95lrILk 485 | [6800]: https://github.com/shaunagm/pycon2018-django-tutorial 486 | 487 | [6100]: https://www.youtube.com/watch?v=XphJRQ3AzMU 488 | [61000]: https://github.com/kennethlove/pycon2017 489 | 490 | [6110]: https://www.youtube.com/watch?v=KZHXjGP71kQ 491 | [61100]: https://gswd-a-crash-course-pycon-2014.readthedocs.io/en/latest/ 492 | 493 | [6120]: https://www.youtube.com/watch?v=C0wuTkS93B0 494 | [61200]: https://speakerdeck.com/kennethlove/django-101 495 | [61201]: https://github.com/kennethlove/pycon2016 496 | 497 | [6130]: https://www.youtube.com/watch?v=knUitQQnpJo 498 | [61300]: https://thebuild.com/presentations/pycon-2016-pppp.pdf 499 | 500 | [6140]: https://www.youtube.com/watch?v=5ajZMpTcUZU 501 | [61400]: https://github.com/jacinda/pycon_library 502 | 503 | [6150]: https://www.youtube.com/watch?v=1Va493SMTcY 504 | [6151]: https://www.youtube.com/watch?v=uAtaKr5HOdA 505 | [6152]: https://www.youtube.com/watch?v=P141KRbxVKc 506 | [61500]: https://github.com/zzzeek/sqla_tutorial 507 | [61501]: https://speakerdeck.com/pyconslides/sqlalchemy-session-in-depth-by-mike-bayer 508 | [61502]: https://speakerdeck.com/zzzeek/introduction-to-sqlalchemy-pycon-2013 509 | [6160]: https://www.youtube.com/watch?v=3DLwPcrE5mA 510 | [61600]: https://github.com/cjw296/pycon-uk-2019-fastapi 511 | [6170]: https://youtu.be/rN5t1d3MZDk?t=57 512 | [6180]: https://www.youtube.com/watch?v=kVS8uCxhZws 513 | [61800]: https://greyli.com/slides/pycon2021 514 | 515 | [710]: https://www.youtube.com/watch?v=1i8ylq4j_EY 516 | [7100]: https://speakerdeck.com/pycon2014/its-dangerous-to-go-alone-battling-the-invisible-monsters-in-tech-by-julie-pagano 517 | 518 | [720]: https://www.youtube.com/watch?v=qxE1_MgHXI4 519 | [7200]: https://speakerdeck.com/pycon2014/technical-onboarding-training-and-mentoring-by-kate-heddleston-and-nicole-zuckerman 520 | 521 | [730]: https://www.youtube.com/watch?v=RbeHBnWfXUc 522 | [7300]: https://speakerdeck.com/pycon2015/kathleen-danielson-avoiding-burnout-and-other-essentials-of-open-source-self-care 523 | 524 | [740]: https://www.youtube.com/watch?v=UV3-w0gvrrU 525 | [7400]: https://speakerdeck.com/pycon2016/lynn-root-noa-resare-why-cant-we-be-friends-do-corporations-and-foss-really-mix 526 | 527 | [750]: https://www.youtube.com/watch?v=-9NpTeddWds 528 | [7500]: https://speakerdeck.com/pycon2018/sara-packman-the-journey-over-the-intermediate-gap 529 | 530 | [760]: https://www.youtube.com/watch?v=49CIIu1XkIE 531 | [7600]: https://speakerdeck.com/pycon2018/joyce-jang-build-teams-as-an-engineer 532 | 533 | [770]: https://www.youtube.com/watch?v=CTWgKyLk6mo 534 | [7700]: https://speakerdeck.com/pycon2019/lauren-schaefer-does-remote-work-really-work 535 | 536 | [810]: https://www.youtube.com/watch?v=_rLPDxpXIFc 537 | [811]: https://www.youtube.com/watch?v=tFalO9KdCDM 538 | [812]: https://www.youtube.com/watch?v=vQjmz9wCjLA 539 | [8100]: https://www.obeythetestinggoat.com/ 540 | [8101]: https://github.com/hjwp/Test-Driven-Django-Tutorial 541 | 542 | [820]: https://www.youtube.com/watch?v=FjojZxDZscQ 543 | [8200]: https://speakerdeck.com/pycon2018/brian-okken-paul-everitt-visual-testing-with-pycharm-and-pytest 544 | 545 | [830]: https://www.youtube.com/watch?v=MYucYon2-lk 546 | [8300]: https://speakerdeck.com/pycon2018/hillel-wayne-beyond-unit-tests-taking-your-testing-to-the-next-level 547 | 548 | [840]: https://www.youtube.com/watch?v=SmBAl34RV4M 549 | [8400]: https://speakerdeck.com/pycon2019/zac-hatfield-dodds-escape-from-auto-manual-testing-with-hypothesis 550 | 551 | [850]: https://www.youtube.com/watch?v=0ysyWk-ox-8 552 | [8500]: https://speakerdeck.com/pycon2019/jes-ford-getting-started-testing-in-data-science 553 | 554 | [860]: https://www.youtube.com/watch?v=aQ6rpLRJsXs 555 | [8600]: https://speakerdeck.com/pycon2019/neil-chazin-strategies-for-testing-async-code 556 | 557 | [910]: https://www.youtube.com/watch?v=sze4yunoxU0 558 | [9100]: https://speakerdeck.com/pycon2019/amanda-sopkin-the-refactoring-balance-beam-when-to-make-changes-and-when-to-leave-it-alone 559 | 560 | [920]: https://www.youtube.com/watch?v=D_6ybDcU5gc 561 | [9200]: https://speakerdeck.com/pycon2016/brett-slatkin-refactoring-python-why-and-how-to-restructure-your-code 562 | 563 | [930]: https://www.youtube.com/watch?v=W-lZttZhsUY 564 | 565 | [940]: https://www.youtube.com/watch?v=ZzKaFJxiDzA 566 | [941]: https://www.youtube.com/watch?v=VlfVwbf58U4 567 | [9400]: https://tinthe.dev/static/refactoring-python.pdf 568 | 569 | [950]: https://www.youtube.com/watch?v=13hVzP3Oofs 570 | [951]: https://www.youtube.com/watch?v=04paHt9xG9U 571 | [9500]: https://github.com/krother/refactoring_tutorial 572 | 573 | [1010]: https://www.youtube.com/watch?v=-X0BiV9n_fQ 574 | [1011]: https://www.youtube.com/watch?v=TpgiFIGXcT4 575 | [1012]: https://www.youtube.com/watch?v=5W715nfJNJw 576 | [1013]: https://youtu.be/z_sIDLVisvA?t=334 577 | [1014]: https://www.youtube.com/watch?v=fH_as3eZ5YU 578 | [10100]: https://docs.google.com/presentation/d/e/ 579 | 580 | [1010]: https://www.youtube.com/watch?v=-X0BiV9n_fQ 581 | [1011]: https://www.youtube.com/watch?v=TpgiFIGXcT4 582 | [1012]: https://www.youtube.com/watch?v=5W715nfJNJw 583 | [1013]: https://youtu.be/z_sIDLVisvA?t=334 584 | [1014]: https://www.youtube.com/watch?v=fH_as3eZ5YU 585 | [10100]: https://docs.google.com/presentation/d/e/2PACX-1vTUIf7LJJpUd4NzInBGRyHnHqoZ4E736sqd6Iwq_ne3_aDXdJlNgO8O57_USzQzFfDx0gA44fniKe5R/pub?slide=id.p 586 | [10101]: https://allendowney.github.io/BayesMadeSimple/ 587 | [10102]: https://github.com/AllenDowney/BayesMadeSimple 588 | [10103]: https://mybinder.org/v2/gh/AllenDowney/BayesMadeSimple/master 589 | [10104]: https://speakerdeck.com/pyconslides/bayesian-statistics-made-simple-by-allen-downey 590 | 591 | [1110]: https://www.youtube.com/watch?v=LgoGcr8xUiI 592 | [1111]: https://www.youtube.com/watch?v=wXnvEzw4hHI 593 | [11100]: https://github.com/aenglander/practical-api-security-python-example-flask 594 | 595 | [1120]: https://www.youtube.com/watch?v=i4CxLpYhkrM 596 | 597 | [1210]: https://www.youtube.com/watch?v=iG6fr81xHKA 598 | [12100]: https://gist.github.com/miguelgrinberg/f15bc03471f610cfebeba62438435508 599 | [12101]: https://speakerdeck.com/miguelgrinberg/asynchronous-python-for-the-complete-beginner 600 | 601 | [1220]: https://youtu.be/gJ7CnUX_7YQ&t=75 602 | [12200]: https://speakerdeck.com/miguelgrinberg/asynchronous-web-development-with-flask 603 | 604 | [1230]: https://youtu.be/M-UcUs7IMIM?t=169 605 | 606 | 607 | 608 | [3.1.1]: https://www.oreilly.com/library/view/head-first-python/9781491919521/ 609 | [3.1.1.1]: https://www.amazon.com/_/dp/1491919531?tag=oreilly20-20 610 | 611 | [3.1.2]: https://www.py4e.com/book 612 | [3.1.2.1]: https://www.amazon.com/Python-Everybody-Exploring-Data/dp/1530051126 613 | 614 | [3.1.3]: https://learnpythonthehardway.org/python3/ 615 | [3.1.3.1]: https://www.amazon.com/dp/0134692888/?tag=devdetailpage02-20 616 | 617 | [3.1.4.1]: https://www.amazon.com/Python-Programming-Absolute-Beginner-3rd/dp/1435455002 618 | 619 | [3.1.5]: https://mitpress.mit.edu/books/introduction-computation-and-programming-using-python-second-edition 620 | [3.1.5.1]: https://www.amazon.com/Introduction-Computation-Programming-Using-Python/dp/0262529629 621 | 622 | [3.1.6.1]: https://www.amazon.com/Python-Programming-Introduction-Computer-Science-dp-1590282752/dp/1590282752 623 | 624 | [3.1.7]: https://www.oreilly.com/library/view/python-crash-course/9781492071266/ 625 | [3.1.7.1]: https://www.amazon.com/Python-Crash-Course-2nd-Edition-dp-1593279280/dp/1593279280 626 | 627 | [3.1.8]: https://nostarch.com/pythonforkids 628 | [3.1.8.1]: https://www.amazon.com/dp/1593274076/?tag=devdetailpage02-20 629 | 630 | [3.1.9]: https://www.oreilly.com/library/view/core-python-programming/0132269937/ 631 | [3.1.9.1]: https://www.amazon.com/Core-Python-Programming-Wesley-Chun/dp/0132269937 632 | 633 | [3.1.10]: https://www.oreilly.com/library/view/programming-python-4th/9781449398712/ 634 | [3.1.10.1]: https://www.amazon.com/_/dp/0596158106?tag=oreilly20-20 635 | 636 | [3.1.11]: https://www.oreilly.com/library/view/programming-python-4th/9781449398712/ 637 | [3.1.11.1]: https://www.amazon.com/_/dp/0596158106?tag=oreilly20-20 638 | 639 | [3.1.12]: https://greenteapress.com/wp/think-python-2e/ 640 | [3.1.12.1]: https://www.amazon.com/Think-Python-Like-Computer-Scientist/dp/1491939362 641 | 642 | [3.2.1]: https://www.murach.com/shop/murach-s-python-programming-2nd-edition-detail 643 | [3.2.1.1]: https://www.amazon.com/Murachs-Python-Programming-Joel-Murach-dp-1943872740/dp/1943872740 644 | 645 | [3.2.2]: https://www.oreilly.com/library/view/python-distilled/9780134173399/ 646 | [3.2.1.2]: https://www.amazon.com/Python-Essential-Reference-Developers-Library-dp-0134173279/dp/0134173279 647 | 648 | [3.2.3]: https://www.oreilly.com/library/view/python-distilled/9780134173399/ 649 | [3.2.1.3]: https://www.amazon.com/Effective-Python-Specific-Software-Development-dp-0134853989/dp/0134853989 650 | 651 | [3.2.4]: https://realpython.com/products/real-python-course/ 652 | [3.2.1.4]: https://www.amazon.com/Python-Tricks-Buffet-Awesome-Features/dp/1775093301 653 | 654 | [3.2.5]: https://leanpub.com/intermediatepython 655 | 656 | [3.2.6]: https://www.packtpub.com/product/python-3-object-oriented-programming-third-edition/9781789615852 657 | [3.2.1.6]: https://www.amazon.com/Python-Object-Oriented-Programming-maintainable-object-oriented-dp-1801077266/dp/1801077266 658 | 659 | [3.2.7]: https://fbeedle.com/our-books/10-problem-solving-with-algorithms-and-data-structures-using-python-2nd-ed-9781590282571.html 660 | [3.2.1.7]: https://www.amazon.com/Problem-Solving-Algorithms-Structures-Python-ebook/dp/B09NF2TXSZ 661 | 662 | [3.2.8]: https://www.oreilly.com/library/view/practices-of-the/9781617296086/ 663 | [3.2.1.8]: https://www.amazon.com/Practices-Python-Pro-Dane-Hillard/dp/1617296082 664 | 665 | [3.3.1]: https://www.oreilly.com/library/view/fluent-python-2nd/9781492056348/ 666 | [3.3.1.1]: https://www.amazon.com/Fluent-Python-Concise-Effective-Programming-dp-1492056359/dp/1492056359 667 | 668 | [3.3.2]: https://www.packtpub.com/product/mastering-python-high-performance/9781783989300 669 | [3.3.2.1]: https://www.amazon.com/Mastering-Python-Performance-Fernando-Doglio/dp/1783989300 670 | 671 | [3.3.3]: https://pragprog.com/titles/bopytest2/python-testing-with-pytest-second-edition/ 672 | [3.3.3.1]: https://www.amazon.com/Python-Testing-pytest-Effective-Scalable-dp-1680508601/dp/1680508601 673 | 674 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-hacker 2 | plugins: 3 | - jekyll-relative-links 4 | relative_links: 5 | enabled: true 6 | collections: true 7 | include: 8 | - notes/chapter-01:%20The-Language-Basics.md 9 | - notes/chapter-02:%20Built-In-func-&-Std-Modules.md 10 | - CONTRIBUTING.md 11 | - README.md 12 | - assets 13 | - CODE_OF_CONDUCT.md 14 | - LICENSE 15 | -------------------------------------------------------------------------------- /assets/Banner1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiseaidev/awesome-python/9bd5cc6b0bf4db812c9d1e8a131f070506677484/assets/Banner1.jpg -------------------------------------------------------------------------------- /assets/Banner2.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiseaidev/awesome-python/9bd5cc6b0bf4db812c9d1e8a131f070506677484/assets/Banner2.PNG -------------------------------------------------------------------------------- /assets/if.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiseaidev/awesome-python/9bd5cc6b0bf4db812c9d1e8a131f070506677484/assets/if.png -------------------------------------------------------------------------------- /assets/if_elif.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiseaidev/awesome-python/9bd5cc6b0bf4db812c9d1e8a131f070506677484/assets/if_elif.png -------------------------------------------------------------------------------- /assets/if_else.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiseaidev/awesome-python/9bd5cc6b0bf4db812c9d1e8a131f070506677484/assets/if_else.png -------------------------------------------------------------------------------- /assets/iterators.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiseaidev/awesome-python/9bd5cc6b0bf4db812c9d1e8a131f070506677484/assets/iterators.png -------------------------------------------------------------------------------- /assets/namespace_memory.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiseaidev/awesome-python/9bd5cc6b0bf4db812c9d1e8a131f070506677484/assets/namespace_memory.png -------------------------------------------------------------------------------- /assets/nested_if_else.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wiseaidev/awesome-python/9bd5cc6b0bf4db812c9d1e8a131f070506677484/assets/nested_if_else.png -------------------------------------------------------------------------------- /notes/chapter-02: Built-In-func-&-Std-Modules.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | # Chapter_02: Built-in functions & Standard Modules. 8 | 9 | Copyright (c) 2022 Mahmoud Harmouch 10 | 11 | --- 12 | 13 | ## **Quotes**. 14 | 15 | > “It’s better to be individual than a clone of someone else.” ― Fennel Hudson 16 | 17 | > “You are amazing person with unique talents. Have faith in your abilities.” ― Lailah Gifty Akita 18 | 19 | > “You can be all that you want to be. Keep dreaming and reach out to your dreams.” ― Lailah Gifty Akita 20 | 21 | > “Be yourself....and make the world adjust!” ― Germany Kent 22 | 23 | --- 24 | 25 | ## Table Of Content (TOC) 26 | 27 | 1. [Functions](#1) 28 | 1.1 [Function's Arguments](#1.1) 29 | 1.2 [Functional Programming](#1.2) 30 |     1.2.1 [Anonymous Functions](#1.2.1) 31 |     1.2.2 [Map](#1.2.2) 32 |     1.2.3 [Filter](#1.2.3) 33 |     1.2.4 [Reduce](#1.2.4) 34 |     1.2.5 [Zip](#1.2.5) 35 | 1.3 [Other Builtin Functions](#1.3) 36 | 2. [File I/O](#2) 37 | 3. [Standard Modules](#3) 38 | 39 | ## 1. Functions. 40 | 41 | A function is an object Like any other thing in python. It takes arguments(parameters) and has the ability to return data. It is defined using the `def` keyword. 42 | 43 | ```python 44 | def function_name(parameters,...): 45 | # internal variables and statements 46 | return some_operation(parameters) 47 | 48 | >>> def mul(a,b): 49 | ... return a * b 50 | ... 51 | ``` 52 | 53 | The `return` statement returns an object which value is, in our case, the result of multiplication of a and b. 54 | 55 | **Function call** 56 | 57 | ```python 58 | >>> a = 10 59 | >>> b = 12.13 60 | >>> callable(mul) 61 | True 62 | >>> type(mul) # so mul is an istance of the 'function' class. 63 | 64 | >>> c = mul(a,b) 65 | >>> c 66 | 121.30000000000001 # See chapter_01 to know why the output looks like that. 67 | >>> c = mul("string",3) 68 | >>> c 69 | 'stringstringstring' 70 | ``` 71 | 72 | A function can be nested and return any data types (tuples, lists, sets, functions): 73 | 74 | ```python 75 | >>> def outer_function(a,b): 76 | ... x = a * b 77 | ... def inner_function(y): 78 | ... return y + x 79 | ... return inner_function 80 | ... 81 | >>> c = outer_function(100,3) # returns a function 82 | >>> c(33) 83 | 333 84 | ``` 85 | 86 | If there isn't any return value, the returned data will be a `None` object(void function): 87 | 88 | ```python 89 | >>> def do_nothing(): 90 | ... pass 91 | ... 92 | >>> do_nothing() 93 | >>> print(do_nothing()) 94 | None 95 | ``` 96 | 97 | ### 1.1. Function's Arguments. 98 | 99 | A function can take any number of parameters. 100 | 101 | ```python 102 | >>> def mul(a, b, c=5): # Default parameter value. 103 | ... return a * b *c 104 | ... 105 | >>> mul(2,3) 106 | 30 107 | >>> mul(a = 2, b = 3) 108 | 30 109 | >>> mul(a = 2, b = 3, c = 2) 110 | 12 111 | >>> mul(a = 2, c = 2) 112 | Traceback (most recent call last): 113 | File "", line 1, in 114 | TypeError: mul() missing 1 required positional argument: 'b' 115 | ``` 116 | 117 | A function can also take a variable number of arguments if an asterisk `*` is placed before the name of the function: 118 | 119 | ```python 120 | >>> def add(a,*b): 121 | ... return a + sum(num for num in b) 122 | ... 123 | >>> add(1,2,3,4,5,6,7) 124 | 28 125 | >>> def do_nothing(*args): 126 | ... return args 127 | ... 128 | >>> do_nothing() 129 | () 130 | >>> do_nothing(1) 131 | (1,) 132 | >>> type(do_nothing()) 133 | 134 | ``` 135 | 136 | So as you can see, `args` is a tuple object. 137 | 138 | ```python 139 | >>> def do_nothing(**kwargs): 140 | ... return kwargs 141 | ... 142 | >>> do_nothing() 143 | {} 144 | >>> type(do_nothing()) 145 | 146 | >>> do_nothing(a = '1') 147 | {'a': '1'} 148 | ``` 149 | 150 | So `kargs` is a dictionary object. 151 | 152 | ## 1.2. Functional Programming. 153 | 154 | Functional Programming is a often used to describe a piece of code that has no effects on other pieces(immutable data). A functional function is a function that does not change the value of data outside it(no shared variables). 155 | 156 | ```python 157 | # Non functional function: 158 | a = 1 159 | def add(b): 160 | global a 161 | a = a + b 162 | return a 163 | 164 | # functional function: 165 | def add(a,b): 166 | return a + b 167 | ``` 168 | 169 | When talking about the elements of functional programming in Python, the following functions are meant: lambda , map , filter , reduce , zip . 170 | 171 | ### 1.2.1 Anonymous Functions. 172 | 173 | An anonymous function, also called lambda function, is a function that doesn't have a name and it is defined using the keyword `lambda`. 174 | 175 | **Syntax** 176 | 177 | > lambda arguments: expression 178 | 179 | > returns a lambda object(iterable) 180 | 181 | ```python 182 | >>> f = lambda x : x ** 3 + x ** 2 - x + 1 183 | >>> f(1) 184 | 2 185 | ``` 186 | 187 | **Why does lambda function exist?** 188 | 189 | The lambda function is best used as a nested function. 190 | 191 | ```python 192 | >>> def add_mul(a,b): 193 | ... return lambda c: (a + b)*c 194 | ... 195 | >>> add_mul(1,3) 196 | . at 0x7f9a36d94170> 197 | >>> add = add_mul(1,3) 198 | >>> add(3) 199 | 12 200 | 201 | # without the use of lambda function, the previous function will be written like: 202 | 203 | >>> def add_mul(a,b): 204 | ... def mul(c): 205 | ... return (a+b)*c 206 | ... return mul 207 | ... 208 | >>> add_mul(1,3) 209 | .mul at 0x7f9a36da1200> 210 | >>> add = add_mul(1,3) 211 | >>> add(3) 212 | 12 213 | ``` 214 | 215 | So as you can tell, it is preferable to use a lambda function when the anonymous function is needed once in a certain part of the code, but not in all the places of the code. 216 | 217 | **Is it faster than a regular function?** 218 | 219 | ```python 220 | # Lambda Function 221 | >>> sum1 = lambda n : sum(n for n in range(n+1)) 222 | # regular function 223 | >>> def sum2(n): 224 | ... return sum(n for n in range(n+1)) 225 | ... 226 | >>> import timeit 227 | >>> timeit.timeit("sum1(100)", "from __main__ import sum1",number = 100000) 228 | 0.8884602810003344 229 | >>> timeit.timeit("sum2(100)", "from __main__ import sum2",number = 100000) 230 | 0.8455167720003374 231 | ``` 232 | 233 | As you can notice, the normal function is slightly faster than the lambda function. 234 | 235 | **lambda functions can be nested** 236 | 237 | ```python 238 | >>> a = lambda a, b : lambda c: (a + b) * c 239 | >>> c = a(1,2) 240 | >>> c 241 | .. at 0x7f2779d50710> 242 | >>> c(2) 243 | 6 244 | ``` 245 | 246 | **Converting a normal function to lambda** 247 | 248 | It is easy to rewrite a given function into a lambda form. All you need is to do is to replace the 'def func_name' with the `lambda` keyword, declare parameters after lambda, and continue the logic of the program after ':'. 249 | 250 | ```python 251 | 252 | def mul(a,b): 253 | return a + b 254 | 255 | lambda a,b : a + b 256 | ``` 257 | 258 | ### 1.2.2 Map. 259 | 260 | `map()` is a built-in function that accepts a **function** and a **sequence**(dataset) as arguments. It works by applying the passed function to each element. Map can replace a loop. 261 | 262 | **Syntax** 263 | 264 | > map(function, sequence) 265 | 266 | > returns an object map(iterable) 267 | 268 | ```python 269 | >>> list_ = ['first', 'second',123] 270 | >>> map(id,list_) # the function is id and the sequence is list_(id for each element). 271 | 272 | >>> list(map(id,list_)) 273 | [140491930055984, 140491930056112, 94057408700992] 274 | ``` 275 | 276 | **Map with lambda** 277 | 278 | ```python 279 | >>> list_ = [2,4,5,7] 280 | >>> list(map(lambda x: x**2,list_)) # it is more convenient to use lambda and not a normal function ! 281 | [4, 16, 25, 49] 282 | >>> list2 = [] 283 | >>> for e in list_: 284 | ... list2.append(e**2) 285 | ... 286 | >>> list2 287 | [4, 16, 25, 49] 288 | >>> timeit.timeit("list2 = list(map(lambda x: x**2,list_))","from __main__ import list_",number=100000) 289 | 0.24455913900055748 # when you convert it to list,it becomes slower 290 | >>> timeit.timeit("map(lambda x: x**2,list_)","from __main__ import list_",number=100000) 291 | 0.02997873599997547 # faster than a loop 292 | >>> timeit.timeit("for e in list_: list2.append(e**2)","from __main__ import list_,list2",number=100000) 293 | 0.18769715700000233 294 | ``` 295 | 296 | ### 1.2.3 Filter. 297 | 298 | `filter()` is a built-in function that filters(selects) items from a sequence of an iterable. Like `map()` function, it takes a **function** and a **sequence** as parameters. 299 | 300 | **Syntax** 301 | 302 | > filter(function, sequence) 303 | 304 | > returns a filter object(iterable). 305 | 306 | **Filter with lambda** 307 | 308 | ```python 309 | >>> list_ = [1,2,3,4,5] 310 | >>> filter(lambda x: x == 2, list_) 311 | 312 | >>> list(filter(lambda x: x == 2, list_)) # it works like a loop with an if statement 313 | [2] 314 | >>> list(filter(lambda x: x % 2 == 0, list_)) # selects even numbers. 315 | [2, 4] 316 | >>> list0 = [1,2,3,4,5] 317 | >>> list1 = [2,4,7,8,9] 318 | >>> inter = list(filter(lambda e: e in list1, list0)) 319 | >>> inter 320 | [2, 4] 321 | >>> list(set(list0) & set(list1)) 322 | [2, 4] 323 | >>> timeit.timeit("list(set(list0) & set(list1))","from __main__ import list0,list1",number = 100000) 324 | 0.1329232750013034 325 | >>> timeit.timeit("list(filter(lambda e: e in list1, list0))","from __main__ import list0,list1",number = 100000) 326 | 0.18562702400049602 327 | >>> timeit.timeit("filter(lambda e: e in list1, list0)","from __main__ import list0,list1",number = 100000) 328 | 0.03419653799937805 329 | >>> timeit.timeit("set(list0) & set(list1)","from __main__ import list0,list1",number = 100000) 330 | 0.10309240099923045 331 | ``` 332 | 333 | **Difference between Map() and Filter()** 334 | 335 | The following example will illustrate the main difference between the two. 336 | 337 | ```python 338 | >>> list(filter(lambda e: e in list1, list0)) # selects(filters) the elements that match the condition: e in list1 339 | [2, 4] 340 | >>> list(map(lambda e: e in list1, list0)) # runs(map) the expression 'e in list1' on list1 341 | [False, True, False, True, False] 342 | >>> list(map(lambda e: e**2, list0)) # squares the numbers in list0 343 | [1, 4, 9, 16, 25] 344 | >>> list(filter(lambda e: e**2, list0)) # does nothing, it returns list0 because e**2 is always True 345 | >>> list(filter(lambda e: True, list0)) 346 | [1, 2, 3, 4, 5] 347 | >>> list(filter(lambda e: False, list0)) 348 | [] 349 | ``` 350 | 351 | ### 1.2.4 Reduce. 352 | 353 | Visit [Python Docs](https://docs.python.org/3/library/functools.html#functools.reduce) for more information. 354 | 355 | `Reduce()` is a built-in function that combines items(e.g. add, mul..) in a sequence of an iterable. Like the previous functions, it takes a **function** and a **sequence** as parameters. But, it returns a single value. 356 | 357 | **Syntax** 358 | 359 | > Reduce(function, sequence) 360 | 361 | > returns a value of the function on the sequence. 362 | 363 | ```python 364 | >>> from functools import reduce 365 | >>> def add(a,b): 366 | ... print(f"{a} + {b}") 367 | ... return a + b 368 | ... 369 | >>> reduce(add,[1,2,3,4,5,6]) 370 | 1 + 2 371 | 3 + 3 372 | 6 + 4 373 | 10 + 5 374 | 15 + 6 375 | 21 376 | >>> reduce(lambda a,b : a+b,[1,2,3,4,5,6]) 377 | 21 378 | ``` 379 | 380 | First, the function adds the first two elements of the sequence. Then the result of the function is used with the third element of the sequence to call the function again, and so on. 381 | 382 | ```python 383 | -----------------------Exercice------------------------- 384 | >>> persons = [{'name': 'Joe', 'weight': 60}, 385 | ... {' name ': 'David', 'weight': 70}, 386 | ... {' name ': 'Emma', 'weight': 55}, 387 | ... {'name': 'Marla'}] 388 | >>> total_weight = 0 389 | >>> count_weight = 0 390 | >>> for person in persons: 391 | ... if 'weight' in person: 392 | ... total_weight += person['weight'] 393 | ... count_weight += 1 394 | ... 395 | >>> average_weight = total_weight / count_weight 396 | >>> print("the average weight is {:.2f}".format(average_weight)) 397 | the average weight is 61.67 398 | 399 | --------------------map filter reduce ------------------ 400 | >>> from functools import reduce 401 | >>> weights = map(lambda x: x['weight'], filter(lambda x: 'weight' in x, persons)) 402 | >>> average_weight = reduce(lambda a,b: a+b , weights) # the weights variable is consumed here! 403 | >>> average_weight/3 404 | 61.666666666666664 405 | >>> list(weights) # already consumed in average_weight! 406 | [] 407 | ``` 408 | 409 | **Using filter() inside map()** 410 | 411 | The elements are first selected by the `filter` function and then the `map` apply the function on these elements. 412 | 413 | ```python 414 | >>> y = map(lambda x: x * x, filter (lambda x: (x >= 5), (3,4,5,6,7,8,9,10,11))) 415 | >>> list(y) 416 | [25, 36, 49, 64, 81, 100, 121] 417 | >>> list(y) 418 | [] 419 | ``` 420 | 421 | **Using map() inside filter()** 422 | 423 | When you use the `map` function inside the `filter` function, the iterations are first handled by the `map` function and then the `filter` condition is applied to them. 424 | 425 | ```python 426 | >>> y = filter (lambda x: (x >= 5), map (lambda x: x * x, (3,4,5,6,7,8,9,10,11))) 427 | >>> list(y) 428 | [9, 16, 25, 36, 49, 64, 81, 100, 121] 429 | ``` 430 | 431 | **Using filter() and map() inside reduce()** 432 | 433 | The internal functions are executed first and then the reduce() function. 434 | 435 | ```python 436 | >>> d = reduce (lambda x, y: x * y, map (lambda x: x + x, filter (lambda x: (x >= 5), (3,4,5,6,7,8,9,10,11)))) 437 | >>> d 438 | 212889600 439 | ``` 440 | 441 | ### 1.2.5 Zip. 442 | 443 | It Concatenates sequences into tuples. 444 | 445 | **Syntax** 446 | 447 | > zip(sequence_1, sequence_2) 448 | 449 | > returns a tuples list. 450 | 451 | ```python 452 | >>> list(zip(range(5),range(2,10))) 453 | [(0, 2), (1, 3), (2, 4), (3, 5), (4, 6)] # stops at the lowest upper band of the two lists(4) 454 | >>> list(zip(range(3,5),range(2,10))) # think of it as two loops run in parallel. 455 | [(3, 2), (4, 3)] 456 | >>> keys = ['name', 'age', 'job'] 457 | >>> values = ['Joe', '22', 'Python Developer'] 458 | >>> dict_ = dict(zip(keys,values)) 459 | >>> dict_ 460 | {'name': 'Joe', 'age': '22', 'job': 'Python Developer'} 461 | ``` 462 | 463 | For more information about functionnal progamming, please refer to [python docs](https://docs.python.org/3.8/howto/functional.html). 464 | 465 | ## 1.3 Other Builtin Functions. 466 | 467 | [Python Docs.](https://docs.python.org/3/library/functions.html) 468 | 469 | These functions are grouped together in the `__builtins__` module. 470 | 471 | ```python 472 | >>> dir(__builtins__) 473 | ['abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 474 | 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 475 | 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 476 | 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 477 | 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 478 | 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 479 | 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 480 | 'tuple', 'type', 'vars', 'zip'] 481 | 73 Functions. 482 | ``` 483 | 484 | **import** 485 | 486 | It is used to import a module from a given list. 487 | 488 | ```python 489 | >>> help(__import__) 490 | __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module 491 | ``` 492 | 493 | The **local** and **global** environment can be passed as a parameter, and fromlist specify the directive. The level is a flag which allows determining if the imports are relative(1,2...n) or absolute( 0). 494 | 495 | ```python 496 | >>> __import__('math', fromlist=['math.pi'],level=0) 497 | 498 | 499 | # Same as the following. 500 | 501 | >>> from math import pi 502 | 503 | >>> globals().items() # the name of the module is stored in the namespace. 504 | dict_items([('__name__', '__main__'), ('__doc__', None), ('__package__', None), ... 505 | ('math', ), 506 | ('pi', 3.141592653589793)]) 507 | ``` 508 | 509 | **abs** 510 | 511 | It returns the absolute value of a given number(reel or complex). 512 | 513 | ```python 514 | >>> abs(-13) 515 | 13 516 | >>> abs(4 + 3j) # returns sqrt(4**2 + 3**2) 517 | 5.0 518 | ``` 519 | 520 | **all** 521 | 522 | ```python 523 | >>> help(all) 524 | all(iterable, /) 525 | Return True if bool(x) is True for all values x in the iterable. 526 | If the iterable is empty, return True. 527 | 528 | >>> list_ = [1,'2',3] 529 | >>> all([isinstance(e, int) for e in list_]) 530 | False 531 | >>> all([]) 532 | True 533 | ``` 534 | 535 | **any** 536 | 537 | ```python 538 | >>> help(any) 539 | any(iterable, /) 540 | Return True if bool(x) is True for any x in the iterable. 541 | 542 | If the iterable is empty, return False. 543 | 544 | >>> list_ = [1,2,3] 545 | >>> any([isinstance(e, int) for e in list_]) 546 | True 547 | ``` 548 | 549 | **ascii** 550 | 551 | ```python 552 | >>> help(ascii) 553 | ascii(obj, /) 554 | Return an ASCII-only representation of an object. 555 | 556 | >>> ascii(0x33) 557 | '51' 558 | >>> type(ascii(0x33)) 559 | 560 | >>> ascii(0x33)[0] 561 | '5' 562 | >>> ascii([1,2,3]) 563 | '[1, 2, 3]' 564 | >>> ascii('213a\asd\t') 565 | "'213a\\x07sd\\t'" 566 | >>> ascii('\a\b\t\n\v\f\r') 567 | "'\\x07\\x08\\t\\n\\x0b\\x0c\\r'" 568 | >>> ascii(0x0B) 569 | '11' 570 | >>> str(int('b',16)) 571 | '11' 572 | from the ascii table $ man ascii 573 | Oct Dec Hex Char Oct Dec Hex Char 574 | ──────────────────────────────────────────────────────────────────────── 575 | 007 7 07 BEL '\a' (bell) 107 71 47 G 576 | 010 8 08 BS '\b' (backspace) 110 72 48 H 577 | 011 9 09 HT '\t' (horizontal tab) 111 73 49 I 578 | 012 10 0A LF '\n' (new line) 112 74 4A J 579 | 013 11 0B VT '\v' (vertical tab) 113 75 4B K 580 | 014 12 0C FF '\f' (form feed) 114 76 4C L 581 | 015 13 0D CR '\r' (carriage ret) 115 77 4D M 582 | ``` 583 | 584 | **bin** 585 | 586 | ```python 587 | bin(number, /) 588 | Return the binary representation of an integer. 589 | 590 | >>> bin(8) 591 | '0b1000' 592 | >>> int('0b1000',2) 593 | 8 594 | ``` 595 | 596 | **bool** 597 | 598 | ```python 599 | >>> help(bool) 600 | Returns True when the argument is true, False otherwise. 601 | 602 | >>> bool([]) 603 | False 604 | >>> bool(()) 605 | False 606 | >>> bool(1) 607 | True 608 | >>> bool("") 609 | False 610 | >>> bool([""]) 611 | True 612 | >>> bool(('')) 613 | False 614 | >>> bool(('',)) 615 | True 616 | ``` 617 | 618 | **breakpoint** 619 | 620 | This function was introduced in Python 3.7 which does the job of importing pdb and calling pdb.set_trace(). 621 | 622 | ```python 623 | >>> help(breakpoint) 624 | breakpoint(...) 625 | breakpoint(*args, **kws) 626 | 627 | Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept 628 | whatever arguments are passed. 629 | 630 | By default, this drops you into the pdb debugger. 631 | 632 | -------without breakpoint---- 633 | # file.py 634 | import pdb 635 | x = 1 636 | y = 2 637 | print ( x ) 638 | pdb.set_trace() 639 | print ( y ) 640 | z = x + y 641 | -------with breakpoint---- 642 | # file.py 643 | x = 1 644 | y = 2 645 | print ( x ) 646 | breakpoint() 647 | print ( y ) 648 | z = x + y 649 | 650 | $ python3 file.py 651 | 652 | -> print ( y ) 653 | (Pdb) l (l stands for list) 654 | 1 x = 1 655 | 2 y = 2 656 | 3 print ( x ) 657 | 4 breakpoint() 658 | 5 -> print ( y ) 659 | 6 z = x + y 660 | [EOF] 661 | (Pdb) x 662 | 1 663 | (Pdb) y 664 | 2 665 | (Pdb) z 666 | *** NameError: name 'z' is not defined 667 | (Pdb) n (n stands for next) 668 | 2 669 | -> z = x + y 670 | (Pdb) n 671 | --Return-- 672 | -> z = x + y 673 | (Pdb) z 674 | 3 675 | (Pdb) n 676 | ``` 677 | 678 | **bytearray** 679 | 680 | Construct a **mutable** bytearray object. 681 | 682 | ```python 683 | bytearray(iterable_of_ints) -> bytearray 684 | >>> bytearray([1,2,3]) 685 | bytearray(b'\x01\x02\x03') 686 | 687 | bytearray(string, encoding[, errors]) -> bytearray 688 | >>> bytearray("123",'utf-8') 689 | bytearray(b'123') 690 | 691 | bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer 692 | >>> bytearray(b'123') 693 | bytearray(b'123') 694 | 695 | bytearray(int) -> bytes array of size given by the parameter initialized with null bytes 696 | >>> bytearray(2) 697 | bytearray(b'\x00\x00') 698 | 699 | bytearray() -> empty bytes array 700 | >>> bytearray() 701 | bytearray(b'') 702 | 703 | >>> a = bytearray(b'123') 704 | >>> a[1] = 3 # mutable 705 | >>> a 706 | bytearray(b'1\x033') 707 | ``` 708 | 709 | **bytes** 710 | 711 | Construct an **immutable** array of bytes. 712 | 713 | ```python 714 | bytes(iterable_of_ints) -> bytes 715 | bytes(string, encoding[, errors]) -> bytes 716 | bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer 717 | bytes(int) -> bytes object of size given by the parameter initialized with null bytes 718 | bytes() -> empty bytes object 719 | 720 | >>> a = bytes([1,2,3]) 721 | >>> a 722 | b'\x01\x02\x03' 723 | >>> a[1] = 1 724 | Traceback (most recent call last): 725 | File "", line 1, in 726 | TypeError: 'bytes' object does not support item assignment 727 | ``` 728 | 729 | **callable** 730 | 731 | Returns True if the passed object is a function or a method. 732 | 733 | ```python 734 | >>> callable(callable) 735 | True 736 | >>> def func(): 737 | ... print("hi there!") 738 | ... 739 | >>> callable(func) 740 | True 741 | >>> string = 'abc' 742 | >>> callable(string) 743 | False 744 | ``` 745 | 746 | **chr** 747 | 748 | Returns a string that represents the character whose ASCII code is the integer argument. 749 | 750 | ```python 751 | >>> help(chr) 752 | chr(i, /) 753 | Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. 754 | 755 | >>> chr(65) 756 | 'A' 757 | >>> chr(50 + 15) 758 | 'A' 759 | >>> ord('A') 760 | 65 761 | ``` 762 | 763 | ** classmethod** 764 | 765 | Converts a function to a class method. A class method is a method which is associated with a class and not with its instances. 766 | 767 | ```python 768 | >>> class car: 769 | ... def __init__(self, speed, model): 770 | ... self.speed = speed 771 | ... self.model = model 772 | ... def run(cls, speed, model): 773 | ... return cls( speed, model) 774 | ... def print(self): 775 | ... print(self.model + "'s speed is: " + str(self.speed)) 776 | ... run = classmethod(run) 777 | ... 778 | >>> car0 = car(50,'mercedes') 779 | >>> car0.print() 780 | mercedes's speed is: 50 781 | >>> car1 = car.run(60,'bmw') 782 | >>> car1.print() 783 | bmw's speed is: 60 784 | ``` 785 | 786 | You can use the `classmethod` as a decorator. 787 | 788 | ```python 789 | >>> class car: 790 | ... def __init__(self, speed, model): 791 | ... self.speed = speed 792 | ... self.model = model 793 | ... @classmethod 794 | ... def run(cls, speed, model): 795 | ... return cls( speed, model) 796 | ``` 797 | 798 | **compile** 799 | 800 | Python allows source code to be compiled on the fly. The result of this compilation can then be interpreted using the exec() or eval() methods. 801 | 802 | ```python 803 | >>> help(compile) 804 | compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) 805 | Compile source into a code object that can be executed by exec() or eval(). 806 | The mode must be 'exec' to compile a module, 'single' to compile a 807 | single (interactive) statement, or 'eval' to compile an expression. 808 | >>> bytes_ = compile("print('Hi There!')", '/dev/null','eval') 809 | >>> exec(bytes_) 810 | Hi There! 811 | ``` 812 | 813 | **complex** 814 | 815 | Returns a complex number. 816 | 817 | ```python 818 | >>> help(complex) 819 | class complex(object) 820 | complex(real=0, imag=0) 821 | >>> complex(3,4) 822 | (3+4j) 823 | ``` 824 | 825 | **credits**, **copyright** 826 | 827 | ```python 828 | >>> credits() 829 | Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands 830 | for supporting Python development. See www.python.org for more information. 831 | >>> copyright() 832 | Copyright (c) 2001-2019 Python Software Foundation. 833 | All Rights Reserved. 834 | 835 | Copyright (c) 2000 BeOpen.com. 836 | All Rights Reserved. 837 | 838 | Copyright (c) 1995-2001 Corporation for National Research Initiatives. 839 | All Rights Reserved. 840 | 841 | Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam. 842 | All Rights Reserved. 843 | ``` 844 | 845 | **delattr** 846 | 847 | Removes an attribute from an object. Equivalent to del object.attribute_name. 848 | 849 | ```python 850 | >>> class car: 851 | ... speed = 10 852 | ... 853 | >>> car.speed 854 | 10 855 | >>> delattr(car,'speed') 856 | >>> car.speed 857 | Traceback (most recent call last): 858 | File "", line 1, in 859 | AttributeError: type object 'car' has no attribute 'speed' 860 | >>> class car: 861 | ... speed = 10 862 | ... 863 | >>> del car.speed 864 | >>> car.speed 865 | Traceback (most recent call last): 866 | File "", line 1, in 867 | AttributeError: type object 'car' has no attribute 'speed' 868 | ``` 869 | 870 | **dict** 871 | 872 | Creates a dictionary object. 873 | 874 | ```python 875 | >>> dict([('key0','val0'),('key1','val1')]) 876 | {'key0': 'val0', 'key1': 'val1'} 877 | ``` 878 | 879 | **dir** 880 | 881 | Returns a list of the object's attributes. 882 | 883 | ```python 884 | >>> dir() # attributes of the namespace 885 | ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'byte_code', 'bytes_', 'car'] 886 | >>> class car: 887 | ... speed = 10 888 | ... model = 'mercedes' 889 | ... 890 | >>> dir(car) 891 | ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'model', 'speed'] 892 | >>> car. # using the key 893 | car.model car.speed 894 | ``` 895 | 896 | **divmod** 897 | 898 | Returns the tuple: ((a-a% b) / b, a% b) which is an integer division followed by modulo. 899 | 900 | ```python 901 | >>> divmod(10,3) 902 | (3, 1) 903 | >>> divmod(1,3) 904 | (0, 1) 905 | ``` 906 | 907 | **enumerate** 908 | 909 | Returns an object of type enumerate from an iterable(e.g. lists or tuples). 910 | 911 | ```python 912 | >>> enumerate(range(10)) 913 | 914 | >>> for index, element in enumerate([1, 2, 3]): 915 | ... print(index, element) 916 | ... 917 | 0 1 918 | 1 2 919 | 2 3 920 | ``` 921 | 922 | **eval** 923 | 924 | ```python 925 | >>> help(eval) 926 | 927 | eval(source, globals=None, locals=None, /) 928 | Evaluate the given source in the context of globals and locals. 929 | 930 | The source may be a string representing a Python expression 931 | or a code object as returned by compile(). 932 | 933 | >>> eval('1+2') 934 | 3 935 | >>> eval('a+2', {'a': 1}) 936 | 3 937 | >>> eval('f"a equal to {a}"', {'a': 1+2}) 938 | 'a equal to 3' 939 | ``` 940 | 941 | **exec** 942 | 943 | Executes a python script. 944 | 945 | ```python 946 | >>> exec('a = 2; print(a)') 947 | 2 948 | >>> exec('f"a equal to {a}"', {'a': 1+2}) # returns nothing 949 | ``` 950 | 951 | If you want to see the difference between eval, exec, and compile, you can refer to the following answer @[stackoverflow](https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile), or you can read [python docs](https://docs.python.org/3.7/library/functions.html#eval) for more details about these functions. 952 | 953 | **exit** 954 | 955 | ```python 956 | >>> exit 957 | Use exit() or Ctrl-D (i.e. EOF) to exit 958 | ``` 959 | 960 | [**filter**](#1.2.3) 961 | 962 | **float**, **format**, **frozenset** 963 | 964 | Explained in _chapter_01_. 965 | 966 | **getattr** 967 | 968 | Returns the attribute's value of an object. Same as object.attr_name. 969 | 970 | ```python 971 | >>> class car: 972 | ... speed = 50 973 | ... 974 | >>> getattr(car,'speed') 975 | 50 976 | >>> car.speed 977 | 50 978 | >>> getattr(car,'speed1') 979 | Traceback (most recent call last): 980 | File "", line 1, in 981 | AttributeError: type object 'car' has no attribute 'speed1' 982 | >>> getattr(car,'speed1','attr not found!') 983 | 'attr not found!' 984 | ``` 985 | 986 | **globals** 987 | 988 | Returns a dictionary containing all the global variables of the namespace. 989 | 990 | ```python 991 | >>> globals() 992 | {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {}, 994 | '__builtins__': , 'car': } 995 | >>> x = 16 996 | >>> globals() 997 | {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {}, 999 | '__builtins__': , 'car': , 'x': 16} 1000 | 1001 | ``` 1002 | 1003 | **hasattr** 1004 | 1005 | Returns True if the object has the given attribute's name. 1006 | 1007 | ```python 1008 | >>> hasattr(car, 'speed') 1009 | True 1010 | ``` 1011 | 1012 | **hash** 1013 | 1014 | Returns a unique hash of an object. 1015 | 1016 | ```python 1017 | >>> x = 'string' 1018 | >>> y = 'string' 1019 | >>> hash(x) 1020 | 5126848504124768093 1021 | >>> hash(y) 1022 | 5126848504124768093 1023 | >>> hash(123) 1024 | 123 1025 | >>> hash(True) 1026 | 1 1027 | >>> hash('0') 1028 | 3652700342679621854 1029 | >>> hash('1') 1030 | -1863168594792410958 1031 | >>> hash('') 1032 | 0 1033 | >>> hash('2') 1034 | -8901682508772374836 1035 | >>> hash('3') 1036 | 4439948147711810720 1037 | >>> hash('4') 1038 | -6245016655141321378 1039 | ``` 1040 | 1041 | **help** 1042 | 1043 | ```python 1044 | >>> help() 1045 | 1046 | Welcome to Python 3.7's help utility! 1047 | 1048 | If this is your first time using Python, you should definitely check out 1049 | the tutorial on the Internet at https://docs.python.org/3.7/tutorial/. 1050 | 1051 | Enter the name of any module, keyword, or topic to get help on writing 1052 | Python programs and using Python modules. To quit this help utility and 1053 | return to the interpreter, just type "quit". 1054 | 1055 | To get a list of available modules, keywords, symbols, or topics, type 1056 | "modules", "keywords", "symbols", or "topics". Each module also comes 1057 | with a one-line summary of what it does; to list the modules whose name 1058 | or summary contain a given string such as "spam", type "modules spam". 1059 | 1060 | help> hash 1061 | 1062 | Help on built-in function hash in module builtins: 1063 | 1064 | hash(obj, /) 1065 | Return the hash value for the given object. 1066 | 1067 | Two objects that compare equal must also have the same hash value, but the 1068 | reverse is not necessarily true. 1069 | ``` 1070 | 1071 | **hex** 1072 | 1073 | Returns a string representing the hexadecimal form of an integer. 1074 | 1075 | ```python 1076 | >>> hex(16) 1077 | '0x10' 1078 | ``` 1079 | 1080 | **id** 1081 | 1082 | Returns a unique identifier of an object. When two objects of immutable type have the same value, the interpreter can decide to keep only one object in memory. 1083 | 1084 | ```python 1085 | >>> string0 = 'abc' 1086 | >>> string1 = 'abc' 1087 | >>> id(string0), id(string1) 1088 | (139658273441008, 139658273441008) 1089 | ``` 1090 | 1091 | **input** 1092 | 1093 | Executes a user-supplied expression. 1094 | 1095 | ```python 1096 | >>> x = input() 1097 | 1 1098 | >>> x 1099 | '1' 1100 | >>> y = eval(input("Enter your number: ")) # same as int(input("Enter your number: ") 1101 | Enter your number: 1 1102 | >>> y 1103 | 1 1104 | ``` 1105 | 1106 | **int** 1107 | 1108 | Converts a string or number to an integer of a given base. 1109 | 1110 | ```python 1111 | >>> int('20',16) 1112 | 32 1113 | >>> int('20',10) 1114 | 20 1115 | >>> int('20') # by default base = 10 1116 | 20 1117 | ``` 1118 | 1119 | **isinstance** 1120 | 1121 | Tests whether an object is of a given type or an instance of a class. 1122 | 1123 | ```python 1124 | >>> isinstance(10, int) 1125 | True 1126 | >>> isinstance('string', str) 1127 | True 1128 | ``` 1129 | 1130 | **issubclass** 1131 | 1132 | Checks if a given class derives from another class. 1133 | 1134 | ```python 1135 | >>> class x: 1136 | ... pass 1137 | ... 1138 | >>> class y(x): 1139 | ... pass 1140 | ... 1141 | >>> issubclass(y,x) 1142 | True 1143 | >>> issubclass(x,y) 1144 | False 1145 | ``` 1146 | 1147 | **iter** 1148 | 1149 | Returns an iterator from a given object. 1150 | 1151 | ```python 1152 | >>> it = iter([1, 2, 3]) 1153 | >>> it 1154 | 1155 | >>> next(it) 1156 | 1 1157 | >>> next(it) 1158 | 2 1159 | >>> next(it) 1160 | 3 1161 | >>> next(it) 1162 | Traceback (most recent call last): 1163 | File "", line 1, in 1164 | StopIteration 1165 | 1166 | >>> x = 0 1167 | >>> def iterator(): 1168 | ... global x 1169 | ... x += 1 1170 | ... return x 1171 | ... 1172 | >>> it = iter(iterator,5) 1173 | >>> it 1174 | 1175 | >>> next(it) 1176 | 2 1177 | >>> next(it) 1178 | 3 1179 | >>> next(it) 1180 | 4 1181 | >>> next(it) 1182 | Traceback (most recent call last): 1183 | File "", line 1, in 1184 | StopIteration 1185 | ``` 1186 | 1187 | **len** 1188 | 1189 | Returns the number of elements in a given sequence. 1190 | 1191 | ```python 1192 | >>> dict = {'key0': 'val0', 'key1': 'val1'} 1193 | >>> len(dict) 1194 | 2 1195 | >>> string = "abc" 1196 | >>> len(string) 1197 | 3 1198 | ``` 1199 | 1200 | **license** 1201 | 1202 | Displays the license information and the history of Python versions. 1203 | 1204 | ```python 1205 | A. HISTORY OF THE SOFTWARE 1206 | ========================== 1207 | 1208 | Python was created in the early 1990s by Guido van Rossum at Stichting 1209 | Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands 1210 | as a successor of a language called ABC. Guido remains Python's 1211 | principal author, although it includes many contributions from others. 1212 | 1213 | In 1995, Guido continued his work on Python at the Corporation for 1214 | National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) 1215 | in Reston, Virginia where he released several versions of the 1216 | software. 1217 | 1218 | In May 2000, Guido and the Python core development team moved to 1219 | BeOpen.com to form the BeOpen PythonLabs team. In October of the same 1220 | year, the PythonLabs team moved to Digital Creations, which became 1221 | Zope Corporation. In 2001, the Python Software Foundation (PSF, see 1222 | https://www.python.org/psf/) was formed, a non-profit organization 1223 | created specifically to own Python-related Intellectual Property. 1224 | Zope Corporation was a sponsoring member of the PSF. 1225 | 1226 | All Python releases are Open Source (see http://www.opensource.org for 1227 | the Open Source Definition). Historically, most, but not all, Python 1228 | Hit Return for more, or q (and Return) to quit: 1229 | ``` 1230 | 1231 | **list** 1232 | 1233 | Generates a new list object. `list_ = list ()` is equivalent to `list_ = []`. 1234 | 1235 | ```python 1236 | >>> list() 1237 | [] 1238 | >>> list({'key0':'val0'}) 1239 | ['key0'] 1240 | >>> list(('a','b')) 1241 | ['a', 'b'] 1242 | >>> list(('abc')) 1243 | ['a', 'b', 'c'] 1244 | ``` 1245 | 1246 | **locals** 1247 | 1248 | Returns a dictionary object containing the local variables of the current scope. 1249 | 1250 | ```python 1251 | >>> def add(a,b): 1252 | ... x = a + b 1253 | ... print(locals()) 1254 | ... 1255 | >>> add(1,2) 1256 | {'a': 1, 'b': 2, 'x': 3} 1257 | ``` 1258 | 1259 | [**map**](#1.2.2) 1260 | 1261 | **max** 1262 | 1263 | Returns the largest element in the sequence. If several sequences are provided, returns the largest one. 1264 | 1265 | ```python 1266 | >>> max(1,2,3) 1267 | 3 1268 | >>> max([1,2,3]) 1269 | 3 1270 | >>> max([1,2,3],[1,2,3,4]) 1271 | [1, 2, 3, 4] 1272 | >>> max([1,2,3],[1,2,3]) 1273 | [1, 2, 3] 1274 | >>> max([1,2,3],[1,3]) 1275 | [1, 3] 1276 | >>> max([1,2,3],[1,2]) 1277 | [1, 2, 3] 1278 | >>> max([1,2,3],[1,5]) 1279 | [1, 5] 1280 | >>> max('abc') 1281 | 'c' 1282 | >>> max('hi', 'Hi') 1283 | 'hi' 1284 | ``` 1285 | 1286 | **memoryview** 1287 | 1288 | Creates a new memoryview object which references the given object. 1289 | 1290 | ```python 1291 | >>> a = bytes(b'\a\bsd') 1292 | >>> a 1293 | b'\x07\x08sd' 1294 | >>> memoryview(a) 1295 | 1296 | >>> memoryview(a) 1297 | 1298 | >>> memoryview(a) 1299 | 1300 | ``` 1301 | 1302 | **min** 1303 | 1304 | Returns the lowest value in a given sequence. 1305 | 1306 | ```python 1307 | >>> min('abcd') 1308 | 'a' 1309 | >>> min(['abcd']) 1310 | 'abcd' 1311 | >>> min(1,2,4) 1312 | 1 1313 | >>> min(1, 2) 1314 | 1 1315 | >>> min([1, 2], [1]) 1316 | [1] 1317 | >>> min([1, 3], [1, 2]) 1318 | [1, 2] 1319 | >>> min([3, 1], [1, 2]) 1320 | [1, 2] 1321 | >>> min([1, 1], [1, 2]) 1322 | [1, 1] 1323 | >>> min([1, 1], [2, 1]) 1324 | [1, 1] 1325 | ``` 1326 | 1327 | **next** 1328 | 1329 | Returns the next element of an iterable. 1330 | 1331 | ```python 1332 | >>> it = iter([1,2,3,4,5]) 1333 | >>> next(it) 1334 | 1 1335 | >>> next(it) 1336 | 2 1337 | >>> next(it) 1338 | 3 1339 | ``` 1340 | 1341 | **object** 1342 | 1343 | Creates an object without any features. 1344 | 1345 | ```python 1346 | >>> a = object() 1347 | >>> a 1348 | 1349 | >>> object() == object() 1350 | False 1351 | >>> object() is object() 1352 | False 1353 | ``` 1354 | 1355 | **oct** 1356 | 1357 | Returns an octal representation of an integer. 1358 | 1359 | ```python 1360 | >>> oct(8) 1361 | '0o10' 1362 | ``` 1363 | 1364 | **open** 1365 | 1366 | Returns a file object. 1367 | 1368 | ```python 1369 | >>> f = open('replay_pid4677.log') 1370 | >>> f 1371 | <_io.TextIOWrapper name='replay_pid4677.log' mode='r' encoding='UTF-8'> 1372 | >>> f.readline() 1373 | 'JvmtiExport can_access_local_variables 0\n' 1374 | ``` 1375 | 1376 | **ord** 1377 | 1378 | Returns an integer Unicode code value of a character. 1379 | 1380 | ```python 1381 | >>> ord('a') 1382 | 97 1383 | >>> list(map(ord,'asdqwr')) 1384 | [97, 115, 100, 113, 119, 114] 1385 | ``` 1386 | 1387 | **pow** 1388 | 1389 | Computes the power for a given number. It is equivalent to x ** y and (x ** y)% z. 1390 | 1391 | ```python 1392 | >>> pow(3,2) # 3**2 1393 | 9 1394 | >>> pow(3,2,2) # 3**2 % 2 1395 | 1 1396 | ``` 1397 | 1398 | **print** 1399 | 1400 | Displays values ​​to the data stream or `sys.stdout` by default. `sys.stdout` or the system standard output means the function `print` will print the value to the screen. It can be changed to `stdin` or `stderr`. 1401 | 1402 | ```python 1403 | >>> type(print) 1404 | 1405 | >>> print(1,2,3,4, sep = ' ,') 1406 | 1 ,2 ,3 ,4 1407 | >>> print(1,2,3,4, sep = '\n') 1408 | 1 1409 | 2 1410 | 3 1411 | 4 1412 | >>> print(1,2,3,4) # by default sep = " " 1413 | 1 2 3 4 1414 | >>> print(1,2,3,4, sep = '\n', end = '<---\n') # by default end = "\n" 1415 | 1 1416 | 2 1417 | 3 1418 | 4<--- 1419 | ``` 1420 | 1421 | **property** 1422 | 1423 | Creates a property from an object attribute. 1424 | 1425 | ```python 1426 | >>> class A: 1427 | ... __a = 1 1428 | ... def set_a(self, val): 1429 | ... self.__a = val 1430 | ... def get_a(self): 1431 | ... return self.__a 1432 | ... a = property(get_a, set_a) 1433 | ... 1434 | >>> a = A 1435 | >>> a.a 1436 | 1 1437 | >>> a.a = 10 1438 | >>> a.a 1439 | 10 1440 | ``` 1441 | 1442 | You can use `@property` decorator instead of calling the property object. 1443 | 1444 | ```python 1445 | >>> class A: 1446 | ... __a = 1 1447 | ... @property 1448 | ... def set_a(self, val): 1449 | ... self.__a = val 1450 | ... @property 1451 | ... def get_a(self): 1452 | ... return self.__a 1453 | ... 1454 | ``` 1455 | 1456 | **quit** 1457 | 1458 | Allows you to exit the REPL. 1459 | 1460 | ```python 1461 | >>> quit 1462 | Use quit() or Ctrl-D (i.e. EOF) to exit 1463 | ``` 1464 | 1465 | **range** 1466 | 1467 | Returns a range objectg indicating the start and the end. By default step = 1 and start 0. 1468 | 1469 | ```python 1470 | >>> range 1471 | 1472 | >>> range(3) 1473 | range(0, 3) 1474 | >>> list(range(3)) 1475 | [0, 1, 2] 1476 | >>> list(range(1,9,2)) 1477 | [1, 3, 5, 7] 1478 | >>> list(range(9,2,-1)) 1479 | [9, 8, 7, 6, 5, 4, 3] 1480 | >>> list(range()) 1481 | Traceback (most recent call last): 1482 | File "", line 1, in 1483 | TypeError: range expected 1 arguments, got 0 1484 | >>> for i in range(5): 1485 | ... print(i, end = ', ') 1486 | ... 1487 | 0, 1, 2, 3, 4, 1488 | ``` 1489 | 1490 | **repr** 1491 | 1492 | Returns a functional representation as a string of a object. 1493 | 1494 | ```python 1495 | >>> list_ = [1,2,3] 1496 | >>> list_ 1497 | [1, 2, 3] 1498 | >>> repr(list_) 1499 | '[1, 2, 3]' 1500 | >>> list_.__repr__() 1501 | '[1, 2, 3]' 1502 | >>> eval(repr(list_)) 1503 | [1, 2, 3] 1504 | >>> eval(repr(list_)) == list_ 1505 | True 1506 | >>> eval(repr(list_)) == eval(list_.__repr__()) 1507 | True 1508 | ``` 1509 | 1510 | **reversed**[chapter_01] 1511 | 1512 | **round** 1513 | 1514 | Round off a number based on n digits precision. 1515 | 1516 | ```python 1517 | >>> pi = 3.141592 1518 | >>> round(pi,3) 1519 | 3.142 1520 | >>> round(pi,0) 1521 | 3.0 1522 | >>> round(pi) 1523 | 3 1524 | >>> n = 31234.1232 1525 | >>> round(n, -1) 1526 | 31230.0 1527 | >>> round(n, -2) 1528 | 31200.0 1529 | ``` 1530 | 1531 | **set** 1532 | 1533 | Returns an unordered collection of items. Parameter must be a sequence object. 1534 | 1535 | ```python 1536 | >>> set((1,2,3)) 1537 | {1, 2, 3} 1538 | >>> set([1,2,3]) 1539 | {1, 2, 3} 1540 | >>> set([1,2,3]).pop() 1541 | 1 1542 | ``` 1543 | 1544 | **setattr** 1545 | 1546 | Allows you to change the value of an attribute for a given object. Equivalent to 1547 | object.attr = val. 1548 | 1549 | ```python 1550 | >>> class A: 1551 | ... a 1552 | ... 1553 | >>> a = A 1554 | >>> a.a = 10 1555 | >>> a.a 1556 | 10 1557 | >>> setattr(a, 'a', 20) 1558 | >>> a.a 1559 | 20 1560 | ``` 1561 | 1562 | **slice** 1563 | 1564 | Creates a slice object. It is used for extended slicing (e.g. a[0:5:2]: a[0], a[2], a[4]) 1565 | 1566 | ```python 1567 | >>> list_ = [1,2,3,4,5,6] 1568 | >>> list_[1:3:1] 1569 | [2, 3] 1570 | >>> list_[1:1:1] 1571 | [] 1572 | >>> list_[2:0:2] 1573 | [] 1574 | >>> list_[-4::2] 1575 | [3, 5] 1576 | >>> list_[-4:-8:-2] 1577 | [3, 1] 1578 | ``` 1579 | 1580 | **sorted** 1581 | 1582 | Returns a list of sorted items based on the items of the iterable object. 1583 | 1584 | ```python 1585 | >>> sorted(['c', 'a', 'b', 'd', 'h']) 1586 | ['a', 'b', 'c', 'd', 'h'] 1587 | >>> sorted(['c', 'a', 'b', 'd', 'h']) 1588 | ['a', 'b', 'c', 'd', 'h'] 1589 | >>> sorted(['c', 'a', 'b', 'd', 'h'], reverse = True) 1590 | ['h', 'd', 'c', 'b', 'a'] 1591 | >>> def key(e): 1592 | ... r = -ord(e) 1593 | ... print(f"key({e}) = {r}") 1594 | ... return r 1595 | ... 1596 | >>> sorted(['c', 'a', 'b', 'd', 'h'], key=key) 1597 | key(c) = -99 1598 | key(a) = -97 1599 | key(b) = -98 1600 | key(d) = -100 1601 | key(h) = -104 1602 | ['h', 'd', 'c', 'b', 'a'] 1603 | >>> def key(e): 1604 | ... res = ord(e) 1605 | ... print(f"key({e}) = {res}") 1606 | ... return res 1607 | ... 1608 | >>> sorted(['c', 'a', 'b', 'd', 'h'], key=key) 1609 | key(c) = 99 1610 | key(a) = 97 1611 | key(b) = 98 1612 | key(d) = 100 1613 | key(h) = 104 1614 | ['a', 'b', 'c', 'd', 'h'] 1615 | ``` 1616 | 1617 | **staticmethod** 1618 | 1619 | Transforms a function into a static method. A static method is a method that is independent of the class instance. 1620 | 1621 | ```python 1622 | >>> class A: 1623 | ... def add(a,b): 1624 | ... return a + b 1625 | ... add = staticmethod(add) 1626 | ... 1627 | >>> A.add(1,3) 1628 | 4 1629 | >>> a = A() 1630 | >>> a.add(3,5) 1631 | 8 1632 | ``` 1633 | 1634 | The last statement of the class be replaced by a decorator. 1635 | 1636 | ```python 1637 | >>> class A: 1638 | ... @staticmethod 1639 | ... def add(a,b): 1640 | ... return a + b 1641 | ... 1642 | >>> A.add(1,3) 1643 | 4 1644 | >>> a = A() 1645 | >>> a.add(3,5) 1646 | 8 1647 | ``` 1648 | 1649 | **str** 1650 | 1651 | Returns a visual representation of the object as a string object. If the object 1652 | is a string object, then str(object) is equal to object. 1653 | 1654 | ```python 1655 | >>> str(()) 1656 | '()' 1657 | >>> str() 1658 | '' 1659 | >>> str([]) 1660 | '[]' 1661 | >>> str(5) 1662 | '5' 1663 | >>> str('5') 1664 | '5' 1665 | >>> str("5") 1666 | '5' 1667 | ``` 1668 | 1669 | **sum** 1670 | 1671 | Returns the sum of all elements of a sequence. 1672 | 1673 | ```python 1674 | >>> sum([1,3,4,5],3) 1675 | 16 1676 | >>> sum([1,3,4,5]) 1677 | 13 1678 | >>> sum([],123) 1679 | 123 1680 | ``` 1681 | 1682 | **super** 1683 | 1684 | It is frequently used when a method is overloaded in descendant classes. 1685 | 1686 | ```python 1687 | >>> class A: 1688 | ... def __init__(self): 1689 | ... print("A.__init__()") 1690 | ... 1691 | >>> class B(A): 1692 | ... def __init__(self): 1693 | ... print("B.__init__()") 1694 | ... super().__init__() 1695 | ... 1696 | >>> class C(B): 1697 | ... def __init__(self): 1698 | ... print("C.__init__()") 1699 | ... super().__init__() 1700 | ... 1701 | >>> c = C() 1702 | C.__init__() 1703 | B.__init__() 1704 | A.__init__() 1705 | 1706 | ``` 1707 | 1708 | **type** 1709 | 1710 | Returns the type of an object. The test of an object's type is equivalent to `isinstance(type, object)`. 1711 | 1712 | ```python 1713 | >>> help(type) 1714 | 1715 | class type(object) 1716 | | type(object_or_name, bases, dict) 1717 | | type(object) -> the object's type 1718 | | type(name, bases, dict) -> a new type 1719 | 1720 | >>> type("asd") 1721 | 1722 | >>> type("asd") == str 1723 | True 1724 | >>> isinstance("asd", str) 1725 | True 1726 | 1727 | type(name, bases, dict) -> a new type 1728 | This notation is used to avoid an explicit definition of the new type. 1729 | >>> new = type('New', (str, ), dict(a ='1')) 1730 | >>> new 1731 | 1732 | >>> class New(str): 1733 | ... a = '1' 1734 | ``` 1735 | 1736 | **vars** 1737 | 1738 | If the object is not provided, vars() is equivalent to locals(). Otherwise, vars(object) is equivalent to object.** dict**. 1739 | 1740 | ```python 1741 | >>> vars() 1742 | {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {}, '__builtins__': , 'bytes_': at 0x7f65de2731e0, file "/dev/null", line 1>, 'A': , 'B': , 'C': , 'c': <__main__.C object at 0x7f65de15c390>, 'MyType': , 'new': , 'New': } 1743 | >>> locals() 1744 | {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': , '__spec__': None, '__annotations__': {}, '__builtins__': , 'bytes_': at 0x7f65de2731e0, file "/dev/null", line 1>, 'A': , 'B': , 'C': , 'c': <__main__.C object at 0x7f65de15c390>, 'MyType': , 'new': , 'New': } 1745 | >>> vars(new) 1746 | mappingproxy({'a': '1', '__module__': '__main__', '__dict__': , '__weakref__': , '__doc__': None}) 1747 | >>> new.__dict__ 1748 | mappingproxy({'a': '1', '__module__': '__main__', '__dict__': , '__weakref__': , '__doc__': None}) 1749 | ``` 1750 | 1751 | **zip** 1752 | 1753 | Concatenates sequences. 1754 | 1755 | ```python 1756 | >>> list(zip([1,2,3],[4,5,6])) 1757 | [(1, 4), (2, 5), (3, 6)] 1758 | >>> list(map(lambda x, y : (x,y), [1,2,3],[4,5,6])) 1759 | [(1, 4), (2, 5), (3, 6)] 1760 | >>> for i, j in zip([1,2,3],[4,5,6]): 1761 | ... print(i, j) 1762 | ... 1763 | 1 4 1764 | 2 5 1765 | 3 6 1766 | ``` 1767 | 1768 | ## 2. File I/O. 1769 | 1770 | ### 2.1 Opening a file. 1771 | 1772 | Before reading from and writing to a file, you need to open it. Using the built-in open() function, you can create an object of type file, which you can work on. 1773 | 1774 | **syntax** 1775 | 1776 | ```python 1777 | f = open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) 1778 | ``` 1779 | 1780 | | mode | Description | 1781 | | ----- | ------------------------------------------------------------------------------------------------------------ | 1782 | | `r` | Opens the file as **read-only** with a pointer placed at the beginning of a given file. | 1783 | | `rb` | Opens a file for **reading** in **binary** format. | 1784 | | `r+` | Opens a file for **reading** and **writing**. | 1785 | | `rb+` | Opens a file for **reading** and **writing** in binary format. | 1786 | | `w` | Opens a file for **writing** only. Creates a file if it does not exist. | 1787 | | `wb` | Opens a file for **writing** in **binary** format. Creates a file if it doesn't exist. | 1788 | | `w+` | Opens a file for **reading** and **writing**. Creates a file if it does not exist. | 1789 | | `wb+` | Opens a file for **reading** and **writing** in **binary** format. Creates a file if it does not exist. | 1790 | | `a` | Opens for writing, **appending** to the end of the file if it exists. The pointer is at the end of the file. | 1791 | | `ab` | Opens for writing, **appending** in **binary** to the end of the file if it exists. | 1792 | | `a+` | Opens a file for **appending** and **reading**. The pointer is at the end of the file. | 1793 | | `ab+` | Opens a file for **appending** and **reading** in **binary** format. The pointer is at the end of the file. | 1794 | 1795 | ```python 1796 | >>> f = open("file.txt", "w") 1797 | >>> f. 1798 | f.buffer f.fileno( f.newlines f.seek( f.write_through 1799 | f.close( f.flush( f.read( f.seekable( f.writelines( 1800 | f.closed f.isatty( f.readable( f.tell( 1801 | f.detach( f.line_buffering f.readline( f.truncate( 1802 | f.encoding f.mode f.readlines( f.writable( 1803 | f.errors f.name f.reconfigure( f.write( 1804 | >>> f.mode 1805 | 'w' 1806 | >>> f.name 1807 | 'file.txt' 1808 | >>> f.closed 1809 | f.closed 1810 | >>> f.closed 1811 | False 1812 | >>> f.encoding 1813 | 'UTF-8' 1814 | ``` 1815 | 1816 | ### 2.2 Reading from a file. 1817 | 1818 | The `file.read(size)` and `file.readline(size)` method reads a line from an opened file. 1819 | 1820 | ```python 1821 | >>> help(f.read) 1822 | 1823 | read(size=-1, /) method of _io.TextIOWrapper instance 1824 | Read at most n characters from stream. 1825 | 1826 | >>> f = open("file.txt", "r") 1827 | >>> f 1828 | <_io.TextIOWrapper name='file.txt' mode='r' encoding='UTF-8'> 1829 | >>> f.read(10) 1830 | 'line 1 <--' 1831 | >>> f.read(-1) # by default, size = -1; f.read() 1832 | '-\nline 2 <---\nline 3 <---\nline 4 <---\nline 5 <---\nline 6 <---\nline 7 <---\nline 8 <---\nline 9 <---\nline 10 <---' 1833 | 1834 | >>> help(f.readline) 1835 | 1836 | readline(size=-1, /) method of _io.TextIOWrapper instance 1837 | Read until newline or EOF. 1838 | 1839 | >>> f.readline() 1840 | 'line 1 <---\n' 1841 | >>> f.readline() # Reads the first line. 1842 | 'line 2 <---\n' 1843 | >>> f.readline(3) # Reads the third line. 1844 | 'lin' 1845 | >>> f.readline(5) 1846 | 'e 1 <' 1847 | >>> f.tell() # Tells the position of the pointer. 1848 | 5 1849 | >>> help(f.readlines) 1850 | 1851 | readlines(hint=-1, /) method of _io.TextIOWrapper instance 1852 | Return a list of lines from the stream. 1853 | 1854 | >>> f.readlines() 1855 | ['---\n', 'line 2 <---\n', 'line 3 <---\n', 'line 4 <---\n', 'line 5 <---\n', 'line 6 <---\n', 'line 7 <---\n', 'line 8 <---\n', 'line 9 <---\n', 'line 10 <---'] 1856 | 1857 | To move the pointer to a given position, use the seek() function. 1858 | 1859 | >>> f.seek(0) 1860 | 0 1861 | >>> f.tell() 1862 | 0 1863 | ``` 1864 | 1865 | ### 2.3 Writing to a file. 1866 | 1867 | The `write()` function is used to write to a file opened in write mode. If the file does not exist, then a new one will be created. 1868 | 1869 | ```python 1870 | >>> f = open('file1.txt', 'w') 1871 | >>> help(f.write) 1872 | 1873 | write(text, /) method of _io.TextIOWrapper instance 1874 | Write string to stream. 1875 | Returns the number of characters written (which is always equal to 1876 | the length of the string). 1877 | 1878 | >>> f.write('Hi \n There!') 1879 | 11 1880 | >>> len('Hi \n There!') 1881 | 11 1882 | ``` 1883 | 1884 | ### 2.4 Closing a file. 1885 | 1886 | The `close()` method automatically closes the file, and any unsaved information is lost. 1887 | 1888 | ```python 1889 | >>> f = open('file1.txt', 'r') 1890 | >>> f.readline() 1891 | 'Hi \n' 1892 | >>> f.readline() 1893 | ' There!' 1894 | >>> f.closed 1895 | False 1896 | >>> f.close() 1897 | >>> f.closed 1898 | True 1899 | ``` 1900 | 1901 | ## 3. [Standard Modules.](https://docs.python.org/3/library/index.html) 1902 | 1903 | Standard modules can be divided into groups by topic. 1904 | 1905 | pathlib — Object-oriented filesystem paths 1906 | os.path — Common pathname manipulations 1907 | fileinput — Iterate over lines from multiple input streams 1908 | stat — Interpreting stat() results 1909 | filecmp — File and Directory Comparisons 1910 | tempfile — Generate temporary files and directories 1911 | glob — Unix style pathname pattern expansion 1912 | fnmatch — Unix filename pattern matching 1913 | linecache — Random access to text lines 1914 | shutil — High-level file operations 1915 | 1916 | | Topic | Modules | 1917 | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | 1918 | | Internet Data Handling | base64, binhex, binascii, email, json, mailbox, mailcap, mimetypes, quopri, uu. | 1919 | | Development Tools | unittest, typing , pydoc, doctest, test, 2to3. | 1920 | | Debugging and Profiling | cProfile, faulthandler , pdb, profile, trace, tracemalloc. | 1921 | | Graphical | IDLE, PyGObject, PyGTK, PyQt, PySide2, wxPython, Tkinter. | 1922 | | Internet Protocols | cgi, cgitb, imaplib, ipaddress, nntplib, poplib, smtplib, socket, syncore, telnetlib, urllib, urllib2. | 1923 | | Platform | UNIX: pwd , grp , fcntl , resource , termios. | 1924 | | Language Services | ast, compileall, dis, keyword, parser, pickletools, pyclbr, py_compile, symbol, symtable, tabnanny, token, tokenize. | 1925 | | Networking | asyncio, asynchat, asyncore, mmap, select, selectors, signal, socket, ssl. | 1926 | | Concurrent Execution | concurrent.futures, multiprocessing, multiprocessing.shared_memory, queue, sched, subprocess, threading, \_thread. | 1927 | | OS Services | argparse, ctypes, curses, curses.ascii, curses.panel, curses.textpad, errno, io, logging, logging.config, logging.handlers , getopt, getpass, platform, time, os. | 1928 | | Cryptographic Services | hashlib, hmac, secrets. | 1929 | | File Formats | configparser, csv, netrc, plistlib, xdrlib. | 1930 | | Data Compression | bz2, gzip, lzma, tarfile, zlib, zipfile. | 1931 | | Data Persistence | copyreg, dbm, marshal, pickle, shelve, sqlite3. | 1932 | | File and Directory Access | filecmp, fileinput, fnmatch, glob, linecache, os.path, pathlib, stat, shutil, tempfile. | 1933 | | Functional Programming | functools, itertools , operator. | 1934 | | Numeric and Mathematics | cmath, decimal, fractions, math, numbers, random, statistics. | 1935 | | Data Types | array, bisect, calendar, collections, collections.abc, copy, datetime, enum, graphlib, heapq, pprint, reprlib, types, weakref, zoneinfo. | 1936 | | Runtime Services | array, atexit, calendar, cmath, copy, datetime, gettext, itertools, locale, math, random, sets, struct, sys, traceback. | 1937 | | Text Processing Services | string, re, difflib, textwrap, unicodedata, stringprep, readline, rlcompleter. | 1938 | | Binary Data Services | struct, codecs. | 1939 | 1940 | ### [base64](https://docs.python.org/3.9/library/base64.html) 1941 | 1942 | This module provides binary data encoding and decoding functions in the formats defined by RFC3548 for base16, base32, and base64. It is used in the HTTP protocol for binary data transmission. 1943 | 1944 | ```python 1945 | >>> dir(base64) 1946 | ['MAXBINSIZE', 'MAXLINESIZE', '_85encode', '_A85END', '_A85START', '__all__', '__builtins__', '__cached__', 1947 | '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_a85chars', '_a85chars2', 1948 | '_b32alphabet', '_b32rev', '_b32tab2', '_b85alphabet', '_b85chars', '_b85chars2', '_b85dec', 1949 | '_bytes_from_decode_data', '_input_type_check', '_urlsafe_decode_translation', '_urlsafe_encode_translation', 1950 | 'a85decode', 'a85encode', 'b16decode', 'b16encode', 'b32decode', 'b32encode', 'b64decode', 'b64encode', 'b85decode', 1951 | 'b85encode', 'binascii', 'bytes_types', 'decode', 'decodebytes', 'decodestring', 'encode', 'encodebytes', 'encodestring', 1952 | 'main', 're', 'standard_b64decode', 'standard_b64encode', 'struct', 'test', 'urlsafe_b64decode', 'urlsafe_b64encode'] 1953 | ``` 1954 | 1955 | #### Base64 encoding and decoding 1956 | 1957 | **b64encode syntax** 1958 | 1959 | `b64encode(s, altchars=None)` 1960 | 1961 | Encodes a bytes-like object `s`. If `altchars` is specified( not None), it is a byte string object of length 2, which defines special characters for the `+` and `/` characters. 1962 | 1963 | ```python 1964 | >>> import base64 1965 | >>> string = "Hi There!" 1966 | >>> bytes_ = string.encode("UTF-8") 1967 | >>> b64 = base64.b64encode(bytes_) # takes a bytes object not string !!! 1968 | >>> b64 1969 | b'SGkgVGhlcmUh' 1970 | >>> type(b64) 1971 | 1972 | >>> type(bytes_) 1973 | 1974 | >>> b64_decode = b64.decode("UTF-8") # converts bytes object to string object. !!! 1975 | >>> b64_decode 1976 | 'SGkgVGhlcmUh' 1977 | >>> type(b64_decode) 1978 | 1979 | ``` 1980 | 1981 | **b64decode syntax** 1982 | 1983 | `b64decode(s, altchars=None, validate=False)` 1984 | 1985 | Decode the Base64 encoded bytes-like object or ASCII string s. It returns as a bytes object. 1986 | 1987 | ```python 1988 | >>> b64_decode = base64.b64decode(b64) 1989 | >>> b64_decode 1990 | b'Hi There!' 1991 | >>> b64_decode.decode('utf-8') 1992 | 'Hi There!' 1993 | ``` 1994 | 1995 | **base64 encode decode a file** 1996 | 1997 | ```python 1998 | >>> import base64 1999 | >>> for line in open("file.txt"): 2000 | ... line_bytes = line.encode('ascii') 2001 | ... line_b64_enc = base64.b64encode(line_bytes) 2002 | ... print(line_b64_enc) 2003 | ... line_decode = base64.b64decode(line_b64_enc) 2004 | ... line_dec = line_decode.decode('ascii') 2005 | ... print(line_dec) 2006 | ... with open("file1.b64", "ab+") as f: # append each line in binairy. 2007 | ... f.write(line_b64_enc) 2008 | ... 2009 | b'bGluZV8wMQkJPC0tLS0tLQo=' 2010 | line_01 <------ 2011 | 2012 | 24 2013 | b'bGluZV8wMiAJPC0tLS0tLQo=' 2014 | line_02 <------ 2015 | 2016 | 24 2017 | b'bGluZV8wMwkJPC0tLS0tLQo=' 2018 | line_03 <------ 2019 | 2020 | 24 2021 | b'bGluZV8wNCAJPC0tLS0tLQo=' 2022 | line_04 <------ 2023 | 2024 | 24 2025 | b'bGluZV8wNSAJPC0tLS0tLQo=' 2026 | line_05 <------ 2027 | 2028 | 24 2029 | b'bGluZV8wNiAJPC0tLS0tLQo=' 2030 | line_06 <------ 2031 | 2032 | 24 2033 | b'bGluZV8wNyAJPC0tLS0tLQ==' 2034 | line_07 <------ 2035 | 24 2036 | 2037 | # content of file1.b64 2038 | bGluZV8wNyAJPC0tLS0tLQ==bGluZV8wMQkJPC0tLS0tLQo=bGluZV8wMiAJPC0tLS0tLQo=bGluZV8wMwkJPC0tLS0tLQo=bGluZV8wNCAJPC0tLS0tLQo=bGluZV8wNSAJPC0tLS0tLQo=bGluZV8wNiAJPC0tLS0tLQo=bGluZV8wNyAJPC0tLS0tLQ== 2039 | ``` 2040 | 2041 | #### Base32 encoding and decoding 2042 | 2043 | ```python 2044 | >>> import base64 2045 | >>> string = "Hi There!" 2046 | >>> bytes_ = string.encode("ascii") 2047 | >>> b32 = base64.b32encode(bytes_) 2048 | >>> b32 2049 | b'JBUSAVDIMVZGKII=' 2050 | >>> b32_decode = base64.b32decode(b32) 2051 | >>> b32_decode 2052 | b'Hi There!' 2053 | >>> b32_decode.decode('ascii') 2054 | 'Hi There!' 2055 | 2056 | ``` 2057 | 2058 | #### hexadecimal(Base16) encoding and decoding 2059 | 2060 | ```python 2061 | >>> import base64 2062 | >>> string = "Hi There!" 2063 | >>> bytes_ = string.encode("ascii") 2064 | >>> b16 = base64.b16encode(bytes_) 2065 | >>> b16 2066 | b'486920546865726521' 2067 | >>> b16_decode = base64.b16decode(b16) 2068 | >>> b16_decode 2069 | b'Hi There!' 2070 | >>> b16_decode.decode('ascii') 2071 | 'Hi There!' 2072 | ``` 2073 | 2074 | ### [binhex](https://docs.python.org/3.9/library/binhex.html) 2075 | 2076 | This module provides binary data encoding and decoding functions in binhex4 format. 2077 | 2078 | **binhex.binhex syntax** 2079 | 2080 | `binhex(infilename, outfilename)` 2081 | 2082 | ```python 2083 | >>> import binhex 2084 | >>> binhex.binhex('file.txt', 'file1.hqx') 2085 | >>> for line in open('file1.hqx', 'r'): 2086 | ... print(line) 2087 | ... 2088 | (This file must be converted with BinHex 4.0) 2089 | 2090 | 2091 | 2092 | :#'CTE'8ZG(Kd!&4&@&3rN!3!N!9f!*!%ET*XD@jPAc!a#3Nm,C!'#QaTEQ9I-$) 2093 | 2094 | J#6`YN!B+E'PZC9m`-`N*2#f3"JTXD@jPAc!d)!Nm,C!'#QaTEQ9I-$8J#6`YN!B 2095 | 2096 | +E'PZC9m`0L!*2#f3"JTXD@jPAc!h)!Nm,C!'2Jd!!!: 2097 | ``` 2098 | 2099 | **binhex.hexbin syntax** 2100 | 2101 | `hexbin(infilename, outfilename)` 2102 | 2103 | ```python 2104 | >>> binhex.hexbin('file1.hqx', 'file1.txt') 2105 | >>> for line in open('file1.txt', 'r'): 2106 | ... print(line) 2107 | ... 2108 | line_01 <------ 2109 | 2110 | line_02 <------ 2111 | 2112 | line_03 <------ 2113 | 2114 | line_04 <------ 2115 | 2116 | line_05 <------ 2117 | 2118 | line_06 <------ 2119 | 2120 | line_07 <------ 2121 | ``` 2122 | 2123 | ### [binascii](https://docs.python.org/3.9/library/binascii.html?highlight=binascii) 2124 | 2125 | Convert between binary and various ASCII-encoded binary representations. 2126 | 2127 | **binascii.a2b_hex, binascii.unhexlify** 2128 | 2129 | Coverts binary data to hexadecimal and returns a bytes object. 2130 | 2131 | ```python 2132 | >>> binascii.b2a_hex('Hi there!'.encode('utf-8')) # input should be a byte object. 2133 | b'486920746865726521' # length = 2 * len(input) = 2 * 9 = 18 2134 | >>> binascii.hexlify('Hi there!'.encode('utf-8')) 2135 | b'486920746865726521' 2136 | ``` 2137 | 2138 | **binascii.a2b_hex, binascii.unhexlify** 2139 | 2140 | Coverts hexadecimal to binary data and returns a bytes object. 2141 | The input should have an even number of hex digits. 2142 | 2143 | ```python 2144 | >>> binascii.unhexlify(b'486920746865726521') 2145 | b'Hi there!' 2146 | >>> binascii.unhexlify(b'486920746865726521').decode('utf-8') 2147 | 'Hi there!' 2148 | >>> binascii.a2b_hex(b'486920746865726521').decode('utf-8') 2149 | 'Hi there!' 2150 | ``` 2151 | 2152 | ### [sys](https://docs.python.org/3.9/library/sys.html?highlight=sys#module-sys) 2153 | 2154 | The sys module contains most of the information relating to the current execution, as well as a series of basic functions and objects of the low level. 2155 | 2156 | **argv** 2157 | 2158 | Contains the list of parameters of a given script. The first element of the list is the name of the script(.py) followed by the list of parameters. 2159 | 2160 | **executable** 2161 | 2162 | Returns the path of the Python interpreter. 2163 | 2164 | ```python 2165 | >>> sys.executable 2166 | '/home/.../bin/python3' 2167 | ``` 2168 | 2169 | **exc_info** 2170 | 2171 | Returns a tuple contains the type of exception, the instance of the exception, and the traceback object(sys.last_type, sys.last_value, sys.last_traceback). 2172 | 2173 | ```python 2174 | >>> import sys 2175 | >>> sys.exc_info() 2176 | (None, None, None) 2177 | >>> try: 2178 | ... a = input() 2179 | ... a = a/3 2180 | ... except: 2181 | ... print(sys.exc_info()) 2182 | ... 2183 | qwe 2184 | (, TypeError("unsupported operand type(s) for /: 'str' and 'int'"), ) 2185 | 2186 | >>> sys.last_type 2187 | 2188 | >>> sys.last_value 2189 | TypeError("unsupported operand type(s) for /: 'str' and 'int'") 2190 | >>> sys.last_traceback 2191 | 2192 | ``` 2193 | 2194 | **platform** 2195 | 2196 | Returns the type of the current running platform. 2197 | 2198 | ```python 2199 | >>> sys.platform 2200 | 'linux' 2201 | ``` 2202 | 2203 | **builtin_module_names** 2204 | 2205 | Returns a tuple of strings containing the names of all available modules. 2206 | 2207 | ```python 2208 | >>> sys.builtin_module_names 2209 | ('_abc', '_ast', '_codecs', '_collections', '_functools', '_imp', '_io', '_locale', '_operator', '_signal', '_sre', 2210 | '_stat', '_string', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', 'atexit', 'builtins', 2211 | 'errno', 'faulthandler', 'gc', 'itertools', 'marshal', 'posix', 'pwd', 'sys', 'time', 'xxsubtype', 'zipimport') 2212 | ``` 2213 | 2214 | **byteorder** 2215 | 2216 | Returns 'big' if the bits are in most significant order(big-Endian), and 'little' if it is in least significant order(little-Endian). 2217 | 2218 | ```python 2219 | >>> sys.byteorder 2220 | 'little' 2221 | ``` 2222 | 2223 | **maxsize** 2224 | 2225 | Returns an integer that represents the maximum value a variable can have. In a 32-bit platform, the value is usually 2 ** 33 - 1 (2147483647), and in a 64-bit platform it is 2 ** 63 - 1 (9223372036854775807). 2226 | 2227 | ```python 2228 | >>> sys.maxsize 2229 | 9223372036854775807 2230 | ``` 2231 | 2232 | **version** 2233 | 2234 | Returns the version of the Python interpreter. 2235 | 2236 | ```python 2237 | >>> sys.version 2238 | '3.7.6 (default, Jan 8 2020, 19:59:22) \n[GCC 7.3.0]' 2239 | ``` 2240 | 2241 | **version_info** 2242 | 2243 | Returns a tuple containing five version number components. 2244 | 2245 | ```python 2246 | >>> sys.version_info 2247 | sys.version_info(major=3, minor=7, micro=6, releaselevel='final', serial=0) 2248 | ``` 2249 | 2250 | **api_version** 2251 | 2252 | Returns the C API version. 2253 | 2254 | ```python 2255 | >>> sys.api_version 2256 | 1013 2257 | ``` 2258 | 2259 | **stdin, stdout, stderr** 2260 | 2261 | standard input, standard output and standard error stream. 2262 | 2263 | ```python 2264 | >>> sys.stdin 2265 | <_io.TextIOWrapper name='' mode='r' encoding='UTF-8'> 2266 | >>> sys.stdout 2267 | <_io.TextIOWrapper name='' mode='w' encoding='UTF-8'> 2268 | >>> sys.stdout.write("Hi there!\n") # print out the message and returns the len of the string. 2269 | Hi there! 2270 | 10 2271 | >>> a = sys.stderr.write("Error\n") 2272 | Error 2273 | ``` 2274 | 2275 | **ps1, ps2** 2276 | 2277 | Returns the primary and the secondary prompt for the interpreter. 2278 | 2279 | ```python 2280 | >>> sys.ps1 2281 | '>>> ' 2282 | >>> sys.ps2 2283 | '... ' 2284 | 2285 | ``` 2286 | 2287 | **implementation** 2288 | 2289 | Returns an object containing information about the running python interpreter. 2290 | 2291 | ```python 2292 | >>> sys.implementation 2293 | namespace(_multiarch='x86_64-linux-gnu', cache_tag='cpython-37', hexversion=50792176, 2294 | name='cpython', version=sys.version_info(major=3, minor=7, micro=6, releaselevel='final', serial=0)) 2295 | ``` 2296 | 2297 | ### [os](https://docs.python.org/3/library/os.html) 2298 | 2299 | The os module groups together 333 functions or objects. 2300 | 2301 | ```python 2302 | >>> len(dir(os)) 2303 | 333 2304 | >>> len([n for n in dir(os) if not n.startswith("_")]) 2305 | 313 2306 | ``` 2307 | -------------------------------------------------------------------------------- /notes/exercises/ex01_readFile.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | f = open("file.txt") 5 | line = f.readline() 6 | 7 | while line: 8 | print(line,end='') 9 | line = f.readline() 10 | f.close() 11 | 12 | with open("file.txt") as f : 13 | line = f.readline() 14 | while line: 15 | print(line,end='\n') 16 | line = f.readline() 17 | # always use the following method, much faster 18 | for line in open("file.txt"): 19 | print(line,end='') 20 | -------------------------------------------------------------------------------- /notes/exercises/ex02_invest.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | 5 | # simple interest formula is I1 = P x R x T. 6 | # compound interest formula is I2 = P(1 + R/n) ^ nT. 7 | """ 8 | Program: invest.py 9 | Author: Harmouch 10 | 11 | 1. The inputs are 12 | starting investment amount. (principal) 13 | number of years. 14 | interest rate (an integer percent) 15 | 16 | 2. The report is displayed in tabular form with a header. 17 | 18 | 3. Computations and outputs: 19 | for each year 20 | compute the interest and add it to the investment 21 | print a formatted row of results for that year 22 | 23 | 4. The ending investment and interest earned are also 24 | displayed. 25 | """ 26 | import sys 27 | if __name__ == "__main__": 28 | try: 29 | p_initial = float(input("[*] Enter the initial capital: ")) # principal = ... $ 30 | R = float(input("[*] Enter the rate ( between 0 and 1 ): "))# the interest rate is ...% 31 | T = int(input("[*] Enter the number of years: ")) # the term is ... years. 32 | n = int(input("[*] Enter the number of compound in a year: ")) 33 | except ValueError: 34 | sys.exit("Please provide valid input!") 35 | # Display the header. 36 | print(f"{'Year': <5} {'Initial Capital': <20} {'Compound Interest': <20} {'Simple Interest': <20} {'Ending balance': <20}") 37 | p_compound = 0 38 | for year in range(1,T+1): 39 | p_compound = p_initial * (1 + R/n) ** (n*year) 40 | p_simple = p_initial * R * year 41 | print(f"{year:<5} {p_initial:<20} {p_compound - p_initial:<20.2f} {p_simple:<20.2f} {p_compound:<20.2f}") 42 | # Display the totals for the period 43 | print(f"Ending balance: {p_compound:<10.2f}$") 44 | print(f"Total interest earned: {p_compound - p_initial:<10.2f}$") 45 | -------------------------------------------------------------------------------- /notes/exercises/ex03_caesarCipherV0.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | """ 4 | Encrypts an input message(lowercase only) and prints the result. 5 | The other input is rotation value. 6 | """ 7 | if __name__ == "__main__": 8 | plainText = input("Enter a message : ").strip().lower() 9 | rot_val = int(input("Enter the rotation value : "))%26 10 | cipher = "" 11 | for char in plainText: 12 | ordvalue = ord(char) 13 | cipherValue = ordvalue + rot_val 14 | ''' 15 | | ord('a')--------ordvalue----------------ord('z') | -----ordvalue + rot_val----- ord('A')| 16 | ''' 17 | if cipherValue > ord('z'): 18 | cipherValue = ord('a') + rot_val - (ord('z') - ordvalue + 1) 19 | cipher += chr(cipherValue) 20 | print("The cipher message is : ",cipher) 21 | -------------------------------------------------------------------------------- /notes/exercises/ex04_caesarDecipherV0.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | """ 4 | Decrypts an encrypted message(lowercase only) and prints its plaintext result. 5 | The other input is rotation value. 6 | """ 7 | if __name__ == "__main__": 8 | cipher = input("Enter an encrypted message : ").strip().lower() 9 | rot_val = int(input("Enter the rotation value : "))%26 10 | plainText = "" 11 | for char in cipher: 12 | ordvalue = ord(char) 13 | plainValue = ordvalue - rot_val 14 | ''' 15 | | ord('a')--------ordvalue----------------ord('z') | -----ordvalue + rot_val----- | 16 | ''' 17 | if plainValue < ord('a'): 18 | plainValue = ord('z') - rot_val + (ord('a') - ordvalue + 1) 19 | plainText += chr(plainValue) 20 | print("The original message is : ",plainText) 21 | -------------------------------------------------------------------------------- /notes/exercises/ex05_base10ToBaseX.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | """ 4 | File: base10tobaseX.py 5 | Converts a decimal integer to a string of digits of baseX. 6 | """ 7 | if __name__ == "__main__": 8 | try: 9 | newBasexNumber = '' 10 | decimal = int(input("Please enter your decimal integer: ")) 11 | baseX = int(input("Please enter baseX(>=2): ")) 12 | if decimal == 0 or baseX <=1: 13 | print("0") 14 | else: 15 | print(f"{'Quotient': <15}{'Remainder': ^15}{'New_Number': >20}") 16 | while decimal > 0: 17 | quotient,remainder = divmod(decimal,baseX) 18 | decimal = quotient 19 | newBasexNumber = str(remainder) + newBasexNumber 20 | print(f"{decimal: <15}{remainder: ^15}{newBasexNumber: >20}") 21 | 22 | print(f"Your number representation in base[{baseX}] : {newBasexNumber}") 23 | except ValueError: 24 | print("Please enter a valid integer!!!") 25 | except Exception: 26 | print("unexpected error occured!!!") 27 | -------------------------------------------------------------------------------- /notes/exercises/ex06_wordsCount.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | """ 4 | File: words_count.py 5 | compute the numbre of words and the average word length in a given sentence . 6 | """ 7 | if __name__ == "__main__": 8 | try: 9 | sentence = input("Enter your sentence: ").strip() 10 | words_list = sentence.split(' ') 11 | count0 = len(words_list) 12 | count1 = sentence.count(' ') + 1 13 | assert count1 == count0 14 | print(f"there are {count0} words in this sentence.") 15 | words_len = [len(word) for word in words_list] 16 | word_avg = sum(words_len)/count0 17 | print(f"the average word length is {word_avg:.2f} letters.") 18 | except Exception as e: 19 | print(e) -------------------------------------------------------------------------------- /notes/exercises/ex07_newtonSquareRoot.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | """ 4 | Compute the square root of a number. 5 | 1. The input is a number. 6 | 2. The outputs are the program's estimate of the square root 7 | using Newton's method of successive approximations, and 8 | Python's own estimate using math.sqrt. 9 | 10 | • real value : 1.414235624 (sqrt(2)) 11 | • formula: new_estimate = old_estimate/2 + x/(old_estimate * 2) 12 | • old_estimate = 1 # initial guess of sqrt(2) (x = 2) 13 | • new_estimate = old_estimate/2 + 1 = 1.5 14 | • new_estimate = new_estimate/2 + 2/3 = 1.41666 15 | • new_estimate = 0.7083 + 2/2.833 = 1.41425 16 | 17 | """ 18 | import math 19 | if __name__ == "__main__": 20 | try : 21 | # Receive the input number from the user 22 | x = float(input("Enter a positive number: ")) 23 | # Initialize the tolerance and estimate 24 | tolerance = 0.000001 25 | estimate = 1.0 26 | # Perform the successive approximations 27 | while True: 28 | estimate = (estimate + x / estimate) / 2 29 | difference = abs(x - estimate ** 2) 30 | if difference <= tolerance: 31 | break 32 | # Output the result 33 | print("The program's estimate:", estimate) 34 | print("Python's estimate:", math.sqrt(x)) 35 | except ValueError: 36 | print("ValueError exception has been raised!") 37 | -------------------------------------------------------------------------------- /notes/exercises/ex08_median.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | """ 4 | Prints the median of a set of numbers in a file. 5 | """ 6 | if __name__ == "__main__": 7 | try: 8 | f = open("numbers.txt", 'r') 9 | # Input the text, convert it to numbers, and 10 | # add the numbers to a list 11 | numbers = [] 12 | for i,line in enumerate(f): 13 | words = line.strip().split(" ") 14 | numbers += list(float(word)for word in words) 15 | # Sort the list and print the number at its midpoint 16 | numbers.sort() 17 | midpoint = len(numbers) // 2 18 | print("The median is", end = " ") 19 | if len(numbers) % 2 == 1: 20 | print(numbers[midpoint]) 21 | else: 22 | print((numbers[midpoint] + numbers[midpoint - 1]) / 2) 23 | except IOError as e: 24 | print(e) 25 | except ValueError as ve: 26 | print(ve) -------------------------------------------------------------------------------- /notes/exercises/ex09_caesarCipherV1.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | """ 4 | Encrypts an input message and prints its cipher result. 5 | The other input is rotation value. 6 | """ 7 | if __name__ == "__main__": 8 | try: 9 | plaintext = input("Enter you text message: ").strip() 10 | shift = int(input("Enter the rotation value: ").strip()) 11 | code = '' 12 | for char in plaintext: 13 | ord_val = ord(char) 14 | isCaps = bool( ord('A') <= ord_val <= ord('Z') ) 15 | if isCaps: 16 | ord_val = ord(char.lower()) # or ord_val -= ord('A') - ord('a') 17 | ord_val -= ord('a') 18 | ord_val = ( ord_val + shift + 26 ) % 26 19 | ord_val += ord('a') 20 | if( isCaps ): 21 | ord_val = ord(chr(ord_val).upper()) # or ord_val += ord('A') - ord('a') 22 | code += chr(ord_val) 23 | print(code) 24 | except ValueError as ve: 25 | print(ve) 26 | 27 | -------------------------------------------------------------------------------- /notes/exercises/ex10_caesarDecipherV1.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | """ 4 | Decrypts a given text file and prints the result. 5 | The other input is rotation value. 6 | """ 7 | if __name__ == "__main__": 8 | try: 9 | code = input("Enter you cipher message: ").strip() 10 | shift = int(input("Enter the rotation value: ").strip()) 11 | plaintext = '' 12 | for char in code: 13 | ord_val = ord(char) 14 | isCaps = bool( ord('A') <= ord_val <= ord('Z') ) 15 | if isCaps: 16 | ord_val = ord(char.lower()) # or ord_val -= ord('A') - ord('a') 17 | ord_val -= ord('a') 18 | ord_val = ( ord_val - shift + 26 ) % 26 19 | ord_val += ord('a') 20 | if( isCaps ): 21 | ord_val = ord(chr(ord_val).upper()) # or ord_val += ord('A') - ord('a') 22 | plaintext += chr(ord_val) 23 | print("Your plaintext message was: ",plaintext) 24 | except ValueError as ve: 25 | print(ve) 26 | -------------------------------------------------------------------------------- /notes/exercises/ex11_caesarCipherV2.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | """ 4 | Encrypts a given text file and prints the result. 5 | The other input is rotation value. 6 | """ 7 | if __name__ == "__main__": 8 | try: 9 | f = open("file.txt", 'r') 10 | shift = int(input("Enter the rotation value: ").strip()) 11 | for i,line in enumerate(f): 12 | linecode = '' 13 | for char in line.strip(): 14 | ord_val = ord(char) 15 | if ord('a') <= ord_val <= ord('z') or ord('A') <= ord_val <= ord('Z') : 16 | isCaps = bool( ord('A') <= ord_val <= ord('Z') ) 17 | if isCaps: 18 | ord_val = ord(char.lower()) # or ord_val -= ord('A') - ord('a') 19 | ord_val -= ord('a') 20 | ord_val = ( ord_val + shift + 26 ) % 26 21 | ord_val += ord('a') 22 | if( isCaps ): 23 | ord_val = ord(chr(ord_val).upper()) # or ord_val += ord('A') - ord('a') 24 | linecode += chr(ord_val) 25 | else: 26 | linecode += char 27 | print(linecode) 28 | f.close() 29 | except ValueError as ve: 30 | print(ve) 31 | except IOError as e: 32 | print(e) -------------------------------------------------------------------------------- /notes/exercises/ex12_caesarDecipherv2.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | """ 4 | Decrypts a given text file and prints the result. 5 | The other input is rotation value. 6 | """ 7 | if __name__ == "__main__": 8 | try: 9 | f = open("file.txt", 'r') 10 | shift = int(input("Enter the rotation value: ").strip()) 11 | for i,line in enumerate(f): 12 | linecode = '' 13 | for char in line.strip(): 14 | ord_val = ord(char) 15 | if ord('a') <= ord_val <= ord('z') or ord('A') <= ord_val <= ord('Z') : 16 | isCaps = bool( ord('A') <= ord_val <= ord('Z') ) 17 | if isCaps: 18 | ord_val = ord(char.lower()) # or ord_val -= ord('A') - ord('a') 19 | ord_val -= ord('a') 20 | ord_val = ( ord_val - shift + 26 ) % 26 21 | ord_val += ord('a') 22 | if( isCaps ): 23 | ord_val = ord(chr(ord_val).upper()) # or ord_val += ord('A') - ord('a') 24 | linecode += chr(ord_val) 25 | else: 26 | linecode += char 27 | print(linecode) 28 | f.close() 29 | except ValueError as ve: 30 | print(ve) 31 | except IOError as e: 32 | print(e) -------------------------------------------------------------------------------- /notes/exercises/ex13_palindrome.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | def is_palindrome_v0(string): 4 | """check if the string is palindrome or not.(for loop) 5 | you need to iterate over the half of the string only""" 6 | for i in range(int(len(string)/2)): 7 | if string[i] != string[-1-i]: 8 | return False 9 | else: 10 | continue 11 | return True 12 | 13 | def is_palindrome_v1(string): 14 | """check if the string is palindrome or not.(while loop)""" 15 | i, n = 0, len(string) - 1 16 | while i < n and string[i] == string[n]: 17 | i += 1 18 | n -= 1 19 | return n <= i 20 | 21 | def is_palindrome_v2(string): 22 | """check if the string is palindrome or not. 23 | if 2 chars are palindrome pop the last item""" 24 | letters = list(string) 25 | for letter in letters: 26 | if letter == letters[-1]: 27 | letters.pop(-1) 28 | else: 29 | return False 30 | return True 31 | 32 | def is_palindrome_v3(string): 33 | """check if the string is palindrome or not using the reversed 34 | built-in method and compare the two lists""" 35 | return list(string) == list(reversed(list(string))) 36 | 37 | def is_palindrome_v4(string): 38 | """check if the string is palindrome or not while checking if the 39 | reversed string begin from index 0""" 40 | return string.find(string[::-1]) == 0 41 | 42 | def is_palindrome_v5(string): 43 | """palindrome recursive version""" 44 | if len(string) <= 1: 45 | return True 46 | if string[0] != string[-1]: 47 | return False 48 | else: 49 | return is_palindrome_v5(string[1:-1]) 50 | 51 | def is_palindrome_v6(string): 52 | """palindrome: check if the first half of the string equal to the second half""" 53 | return True if len(string)<=1 else string[:len(string)//2] == string[-(len(string)//2):][::-1] 54 | # running code 55 | s = "12" 56 | ans0 = is_palindrome_v0(s) 57 | ans1 = is_palindrome_v1(s) 58 | ans2 = is_palindrome_v2(s) 59 | ans3 = is_palindrome_v3(s) 60 | ans4 = is_palindrome_v4(s) 61 | ans5 = is_palindrome_v5(s) 62 | ans6 = is_palindrome_v6(s) 63 | print(ans0, ans1, ans2, ans3, ans4, ans5, ans6) -------------------------------------------------------------------------------- /notes/exercises/ex14_cosine_sineAppr.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | # cosine and sine approximation without using the factorial function! 5 | # cos(x)= 1 - x**2/2! + x**4/4! - x**6/6! + .. 6 | # sin(x)= x - x**3/3! + x**5/5! - x**7/7! + .. 7 | # as you may notice 2! = 2*1; 4! = 4*3*2*1 = 4*3*(2!); 8 | # 6! = 6*5*(4!); in general p! = p*(p-1)*[(p-2)!] knowing (p-2)! 9 | # Taylor polynomial and Lagrange remainder 10 | # formulas https://www.cusd80.com/cms/lib/AZ01001175/Centricity/Domain/5532/LaGrange_Error_Explanation.pdf 11 | import math 12 | 13 | def cosine(x, error): 14 | p = 0 15 | c = 0 16 | appr = 1 17 | term = 1 18 | reminder = abs(x - c) 19 | print(f"{'Iteration':<10}{'term':^25}{'approximation':^25}{'reminder':^25}{'error':^25}") 20 | while reminder > error: 21 | p += 2 22 | term *= - x**2 / (p * (p - 1)) 23 | appr += term 24 | reminder *= abs(x - c)**2 / (p * (p + 1)) 25 | print(f"{p-1:^10}{term:^25.15}{appr:^25.15}{reminder:^25.15}{error:^25.15}") 26 | return appr 27 | 28 | def sine(x, error): 29 | p = 1 30 | c = 0 31 | appr = x 32 | term = 1 33 | reminder = abs(x - c) 34 | print(f"{'Iteration':<10}{'term':^25}{'approximation':^25}{'reminder':^25}{'error':^25}") 35 | while reminder > error: 36 | p += 2 37 | term *= - x**2 / (p * (p - 1)) 38 | appr += term 39 | reminder *= abs(x - c)**2 / (p * (p + 1)) 40 | print(f"{p-1:^10}{term:^25.15}{appr:^25.15}{reminder:^25.15}{error:^25.15}") 41 | return appr 42 | 43 | if __name__ == "__main__": 44 | print("+------------------cosine approximation------------------+") 45 | try: 46 | number = int(input("Enter you number to compute the cosine/sine of it : ")) 47 | error = float(input("Enter the error value : ")) 48 | cos_number = cosine(number,error) 49 | sin_number = sine(number,error) 50 | print(f"Approximation of cos({number}) is: {cos_number:<30.25f}") 51 | print(f"cos({number}) using the math.cos built-in function: {math.cos(number):<30.25f}") 52 | print(f"Approximation of sin({number}) is: {sin_number:<30.25f}") 53 | print(f"sin({number}) using the math.cos built-in function: {math.sin(number):<30.25f}") 54 | except ValueError as e: 55 | print(e) 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /notes/exercises/ex15_pythagoreanTriplets.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | # pythagorean triplets in a range(n): (x,y,z) : x**2 + y**2 = z**2 5 | 6 | import math 7 | def pyTriplet_V0(n): 8 | """returns a pythagorean triplets using generator expressions. 9 | x < y < z 10 | """ 11 | return ((x, y, z) 12 | for x in range(1, n+1) 13 | for y in range(x+1, n+1) 14 | for z in range(y+1, n+1) 15 | if x**2 + y**2 == z**2) 16 | 17 | def pyTriplet_V1(n): 18 | """returns a pythagorean triplets using generator functions. aka lazy tuples ;-) 19 | x < y < z 20 | source : https://stackoverflow.com/questions/575117/generating-unique-ordered-pythagorean-triplets#lang-py%20s-code-block%20hljs%20python 21 | """ 22 | for z in range(1, n+1): 23 | z2= z*z # avoid computing z*z for each iteration in the while loop 24 | x= x2= 1; xstep= 3 25 | y= z - 1; y2= y*y; ystep= 2*y - 1 26 | while x < y: 27 | x2_y2= x2 + y2 28 | if x2_y2 == z2: 29 | yield x, y, z 30 | x+= 1; x2+= xstep; xstep+= 2 31 | y-= 1; y2-= ystep; ystep-= 2 32 | elif x2_y2 < z2: 33 | x+= 1; x2+= xstep; xstep+= 2 34 | else: 35 | y-= 1; y2-= ystep; ystep-= 2 36 | 37 | if __name__ == "__main__": 38 | try: 39 | number = int(input("Enter your number: ")) 40 | triplets0 = pyTriplet_V0(number) 41 | triplets1 = pyTriplet_V1(number) 42 | print(list(triplets0),end='\n\n') 43 | print(sorted(list(triplets1))) 44 | except ValueError as e: 45 | print(e) -------------------------------------------------------------------------------- /notes/exercises/ex16_perfectNumbers.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | def isPerfect(number): 5 | """using generator expressions""" 6 | return sum((divisor for divisor in range(1, number) if number % divisor == 0)) == number 7 | 8 | def divisors(number): 9 | """using generator functions to return a divisor""" 10 | for divisor in range(1,number): 11 | if number % divisor == 0: 12 | yield divisor 13 | 14 | def perfect_list(number): 15 | return [i for i in range(2, number) if isPerfect(i)] 16 | 17 | def sum_(number): 18 | divisors = list(divisor for divisor in range(1,number) if number % divisor == 0) 19 | if sum(divisors) == number: 20 | print('{} = '.format(number) + ' + '.join(str(divisor) for divisor in divisors)) 21 | 22 | if __name__ == "__main__": 23 | try: 24 | number_ = int(input("Enter your number: ")) 25 | for number in perfect_list(number_): 26 | divisors = list(divisor for divisor in range(1,number) if number % divisor == 0) 27 | if sum(divisors) == number: 28 | print('{} = '.format(number) + ' + '.join(str(divisor) for divisor in divisors)) 29 | except ValueError as e: 30 | print(e) -------------------------------------------------------------------------------- /notes/exercises/ex17_primes.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | # https://pypi.org/project/mod/ 5 | from mod import Mod 6 | 7 | def isprime1(number): 8 | # fast 9 | return number > 1 if number <= 3 else len([x for x in range(2, int(number**0.5) + 1) if number % x == 0]) == 0 10 | 11 | def isprime2(number): 12 | # Fermat's Little Theorem 13 | # https://brilliant.org/wiki/fermats-little-theorem/ 14 | # slow 15 | return number > 1 if number <= 3 else len([b for b in range(2,number) if b**(number) != Mod(b,number)]) == 0 16 | 17 | def arecoprime(a, b): 18 | return False if len([i for i in range(2, min(a, b) + 1) 19 | if a % i == 0 and b % i == 0]) != 0 else True 20 | 21 | def coprimes(number): 22 | return (i for i in range(2, number + 1) if arecoprime(i,number)) 23 | 24 | if __name__ == "__main__": 25 | try: 26 | number = int(input("Enter you number: ")) 27 | #print(f"coprimes with {number} are: {list(coprimes(number))} ",end="\n\n") 28 | primes0 = [] 29 | primes1 = [] 30 | for i in range(1,number + 1): 31 | if isprime1(i): 32 | primes0.append(i) 33 | #if isprime2(i): 34 | # primes1.append(i) 35 | print(f"\nPrimes of numbers lower than {number} are: \n{primes0}") 36 | #assert len(primes1) == len(primes0) 37 | assert arecoprime(11, 23) 38 | assert not arecoprime(9, 12) 39 | except ValueError as e: 40 | print(e) -------------------------------------------------------------------------------- /notes/exercises/ex18_MonteCarlo.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | # Pi extimation 5 | # Great explanation: https://brilliant.org/wiki/monte-carlo/ 6 | 7 | import random, math 8 | 9 | def pi_montecarlo(a, b, n): 10 | return 4 * (b -a ) * sum(math.sqrt(1 - random.uniform(a, b)**2) 11 | for i in range(n)) / n 12 | if __name__ == "__main__": 13 | n = int(input("Enter the number of iterations: ")) 14 | print('|' + '-'*98 + '|') 15 | print(f"|{'n':<24}|{'approximation':^24}|{'absolute error':^24}|{'relative error':^23}|") 16 | print('|' + '-'*98+ '|') 17 | for i in range(1,n): 18 | n = 10 ** i 19 | approx = pi_montecarlo( 0, 1, n) 20 | error = math.pi - approx 21 | print(f'|{n:<24}|{approx:^24}|{error:^24}|{abs(error)/math.pi:^23}|') 22 | -------------------------------------------------------------------------------- /notes/exercises/ex19_timeModule.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | import time 5 | 6 | def func1(n): 7 | list_ = [] 8 | for i in range(n): 9 | list_ += [i**2] 10 | return list_ 11 | def func2(n): 12 | list_ = [] 13 | for i in range(n): 14 | list_.append(i**2) 15 | return list_ 16 | def func3(n): 17 | return [i**2 for i in range(n)] 18 | def func4(n): 19 | return (i**2 for i in range(n)) 20 | def time_(func, n = 1000000): 21 | start = time.clock() 22 | func(n) 23 | stop =time.clock() 24 | return stop - start 25 | 26 | if __name__ == "__main__": 27 | print(f"{'+ operator ':-<30}> {time_(func1) :.6f} sec") 28 | print(f"{' append ':-<30}> {time_(func2) :.6f} sec") 29 | print(f"{'list comp ':-<30}> {time_(func3) :.6f} sec") 30 | print(f"{'gen exp ':-<30}> {time_(func4) :.6f} sec") -------------------------------------------------------------------------------- /notes/projets/Project-01: Guess My Number Games/computer_guess.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | if __name__ == "__main__": 5 | print( ''' 6 | /_/_/_/ 7 | .' '. 8 | / o o \ 9 | (| < |) 10 | \ '---' / 11 | '._____.' 12 | ''') 13 | print("Welcome to 'Guess Your Number Game'!") 14 | player_name = input('What is your name?\n') 15 | print("Hello " + player_name + " !") 16 | min_ = 1 17 | max_ = 50 18 | print(f"Think of a number between {min_} and {max_}.") 19 | print("I am trying to guess it in as few attempts as possible.\n") 20 | max_tries = 20; 21 | offset = round((max_ + min_)/2) 22 | guess = offset 23 | for tries in range(max_tries): 24 | answer = input(f"Is your number lower than {guess}?(yes/no)\n") 25 | if answer == 'yes': 26 | guess -= round(offset/2) 27 | else : 28 | guess += round(offset/2) 29 | offset = round(offset/2) 30 | answer = input(f"Is your number equal to {guess}?(yes/no)\n") 31 | if answer == 'yes': 32 | print( ''' 33 | /_/_/_/ 34 | .' '. 35 | / x x \ 36 | (| < |) 37 | \ '---' / 38 | '._____.' 39 | ''') 40 | print("Wohooo! I guessed it! your number was", guess) 41 | print("And it only took me", tries, "tries!\n") 42 | print("Nice!\n") 43 | break 44 | else: 45 | print( ''' 46 | /_/_/_/ 47 | .' '. 48 | / o o \ 49 | (| < |) 50 | \ .---. / 51 | '._____.' 52 | ''') 53 | print("Alright! Let's try again") 54 | if tries == max_tries - 1: 55 | print("I have reached the maximum number of attempts!") 56 | input("\n\nTell me what was your number?") 57 | print("Alright, cool! I will try to guess it next time...") 58 | break 59 | print(f"I only have { max_tries - tries - 1} {'tries' if tries < max_tries - 2 else 'try'} left!\n") 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /notes/projets/Project-01: Guess My Number Games/player_guess.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | import random 5 | import sys 6 | 7 | if __name__ == "__main__": 8 | print( ''' 9 | /_/_/_/ 10 | .' '. 11 | / o o \ 12 | (| < |) 13 | \ '---' / 14 | '._____.' 15 | ''') 16 | print("Welcome to 'Guess My Number Game'!") 17 | player_name = input('What is your name?\n') 18 | print("Hello " + player_name + " !") 19 | min_ = 1 20 | max_ = 50 21 | print(f"I'm thinking of a number between {min_} and {max_}.") 22 | print("Try to guess it in as few attempts as possible.\n") 23 | gen_number = random.randint(min_, max_) 24 | guess = None 25 | max_tries = 20; 26 | for tries in range(max_tries): 27 | try: 28 | input_ = input(f"Take a guess between {min_} and {max_} ('q' to exit)\n") 29 | if input_ == 'q': 30 | sys.exit("Goodbye " + player_name + "!" + " See you later!") 31 | else : 32 | guess = int(input_) 33 | except ValueError: 34 | sys.exit("Not a valid guess! Exiting!") 35 | if guess > gen_number: 36 | print( ''' 37 | /_/_/_/ 38 | .' '. 39 | / o o \ 40 | (| < |) 41 | \ .---. / 42 | '._____.' 43 | ''') 44 | print("Try to guess a lower number...") 45 | elif guess < gen_number: 46 | print( ''' 47 | /_/_/_/ 48 | .' '. 49 | / o o \ 50 | (| < |) 51 | \ .---. / 52 | '._____.' 53 | ''') 54 | print("Try to guess a higher number...") 55 | else: 56 | print( ''' 57 | /_/_/_/ 58 | .' '. 59 | / x x \ 60 | (| < |) 61 | \ '---' / 62 | '._____.' 63 | ''') 64 | print("Congrats! You guessed it! The number was", gen_number) 65 | print("And it only took you", tries, "tries!\n") 66 | print("Nice!\n") 67 | break 68 | if tries == max_tries - 1: 69 | print("You have reached the maximum number of attempts! Hard Luck!") 70 | print("The magic number was", gen_number) 71 | break 72 | print(f"{ max_tries - tries - 1} {'tries' if tries < max_tries - 2 else 'try'} left!\n") 73 | 74 | input("\n\nPress the key to exit...") 75 | 76 | 77 | -------------------------------------------------------------------------------- /notes/projets/Project-02: Word Jumble Game/jumble_word.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | # Word Jumble 5 | # The computer picks a random word and then "jumbles" it 6 | # The player has to guess the original word 7 | import random 8 | # words and hints are extracted from https://www.k5learning.com/worksheets/vocabulary/5th-grade-jumbled-words-1.pdf 9 | WORDS = ['lightly', 10 | 'worth', 11 | 'afford', 12 | 'forward', 13 | 'particular', 14 | 'ruin', 15 | 'practice', 16 | 'clear', 17 | 'natural', 18 | 'taught'] 19 | 20 | HINTS = ['With little weight,force or intensity.', 21 | 'Having a value of.', 22 | 'To be able to manage or bear without serious consequences.', 23 | 'Advance, onward', 24 | 'Of or relating to a single or specific person, thing or event.', 25 | 'A destroyed or decayed building.', 26 | 'Repeated performance to acquire proficiency', 27 | 'Transparent.', 28 | 'Existing in or formed by nature.', 29 | 'Imparted knowledge of or skill in.'] 30 | if __name__ == "__main__": 31 | points = 0 32 | print( 33 | """ 34 | Welcome to Word Jumble! 35 | Unscramble the letters to make a word. 36 | (Press the enter key at the prompt to quit.) 37 | """ 38 | ) 39 | correct = False 40 | playAgain = True 41 | while (playAgain==True): 42 | jumble = "" 43 | correct = False 44 | guesses = 0 45 | # pick one word randomly from the sequence 46 | index = random.randint(0,len(WORDS)-1) # same as random.randrange(len(WORDS)) 47 | word = WORDS[index] 48 | correct_ = word 49 | hint = HINTS[index] 50 | while len(word) or correct_ == jumble: 51 | index = random.randrange(len(word)) 52 | jumble += word[index] 53 | word = word.replace(word[index], '') # remove a char from the string 54 | print("The jumble is:", jumble) 55 | tempPoints = 0 56 | while correct == False: 57 | guess = input("Enter your guess: ").strip().lower() 58 | guesses += 1 59 | if guess == correct_: 60 | print("That's it! You guessed it in only " + str(guesses) + " tries!\n") 61 | tempPoints += len(jumble) * 1.25 # some random points 62 | tempPoints -= round((guesses - 1) / 4.0, 2) # first guess ==> zero 63 | points += tempPoints 64 | print(str(tempPoints) + " points this round and a total of " + str(points) + "!\n") 65 | correct = True 66 | yesNo = input("Would you like to play again? (yes/no): ") 67 | if (yesNo == 'yes'): 68 | playAgain = True 69 | else: 70 | playAgain = False 71 | elif guess == "hint": 72 | tempPoints -= (1.0 / len(jumble)) * 40 73 | print("Hint: " + hint) 74 | correct = False 75 | playAgain = True 76 | elif guess == "quit": 77 | correct = True 78 | playAgain = False 79 | else: 80 | sub = round((1.0 / len(jumble)) * 20,2) 81 | print("Incorrect word, deducting " + str(sub) + " points\n") 82 | tempPoints -= sub 83 | playAgain = True 84 | correct = False 85 | print("Thanks for playing.") 86 | input("\n\nPress the enter key to exit.") 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /notes/projets/Project-03: Tic-Tac-Toe Game/Tic_Tac_Toe.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2022 Mahmoud Harmouch 3 | 4 | # Tic-Tac-Toe 5 | # Plays the game of tic-tac-toe against a human opponent 6 | # global constants 7 | # A modified version of the code from: https://www.cs.ucdavis.edu/~gusfield/cs10sp11/tictactoe.py 8 | X = "X" 9 | O = "O" 10 | TIE = "TIE" 11 | NUM_SQUARES = 9 12 | NUMBERS = "012345678" 13 | 14 | def display_instruct(): 15 | """Display game instructions.""" 16 | print( 17 | """ 18 | Welcome to the greatest intellectual challenge of all time: Tic-Tac-Toe. 19 | This will be a showdown between your human brain and my silicon processor. 20 | You will make your move known by entering a number, 0 - 8. The number 21 | will correspond to the board position as illustrated: 22 | 0 | 1 | 2 23 | --------- 24 | 3 | 4 | 5 25 | --------- 26 | 6 | 7 | 8 27 | Prepare yourself, human. The ultimate battle is about to begin. \n 28 | """ 29 | ) 30 | 31 | def ask_number(question, low, high): 32 | """Ask for a number within a range.""" 33 | response = None 34 | while response not in range(low, high): 35 | response = int(input(question)) 36 | return response 37 | 38 | def pieces(): 39 | """Determine if player or computer goes first.""" 40 | go_first = input("Do you require the first move? (y/n): ").strip().lower() 41 | if go_first == "y": 42 | print("\nThen take the first move. You will need it.") 43 | human = X 44 | computer = O 45 | else: 46 | print("\nYour bravery will be your undoing... I will go first.") 47 | computer = X 48 | human = O 49 | return computer, human 50 | 51 | def display_board(board): 52 | """Display game board on screen.""" 53 | print("\n\t", board[0], "|", board[1], "|", board[2]) 54 | print("\t", "---------") 55 | print("\t", board[3], "|", board[4], "|", board[5]) 56 | print("\t", "---------") 57 | print("\t", board[6], "|", board[7], "|", board[8], "\n") 58 | 59 | def legal_moves(board): 60 | """Returns the empty squares.""" 61 | moves = [] 62 | for square in range(NUM_SQUARES): 63 | if board[square] in NUMBERS: 64 | moves.append(square) 65 | return moves 66 | 67 | def winner(board): 68 | """Determine the game winner.""" 69 | WAYS_TO_WIN = ((0, 1, 2), 70 | (3, 4, 5), 71 | (6, 7, 8), 72 | (0, 3, 6), 73 | (1, 4, 7), 74 | (2, 5, 8), 75 | (0, 4, 8), 76 | (2, 4, 6)) 77 | for row in WAYS_TO_WIN: 78 | if board[row[0]] == board[row[1]] == board[row[2]] not in NUMBERS: 79 | winner = board[row[0]] 80 | return winner 81 | if bool(set(NUMBERS) & set(board)) == False: 82 | return TIE 83 | return None 84 | 85 | def human_move(board, human): 86 | """Get human move.""" 87 | legal = legal_moves(board) 88 | move = None 89 | while move not in legal: 90 | move = ask_number("Where will you move? (0 - 8):", 0, NUM_SQUARES) 91 | if move not in legal: 92 | print("\nThat square is already occupied, foolish human. Choose another.\n") 93 | print("Fine...") 94 | return move 95 | 96 | def computer_move(board, computer, human): 97 | """Make computer move.""" 98 | # make a copy to work with since function will be changing list 99 | board = board[:] 100 | # the best positions to have, in order 101 | BEST_MOVES = (4, 0, 2, 6, 8, 1, 3, 5, 7) 102 | print("I shall take square number", end=" ") 103 | # if computer can win, take that move 104 | for move in legal_moves(board): 105 | temp = board[move] 106 | board[move] = computer 107 | if winner(board) == computer: 108 | print(move) 109 | return move 110 | # done checking this move, undo it 111 | board[move] = temp 112 | 113 | # if human can win, block that move 114 | for move in legal_moves(board): 115 | temp = board[move] 116 | board[move] = human 117 | if winner(board) == human: 118 | print(move) 119 | return move 120 | # done checking this move, undo it 121 | board[move] = temp 122 | # since no one can win on next move, pick best open square 123 | for move in BEST_MOVES: 124 | if move in legal_moves(board): 125 | print(move) 126 | return move 127 | 128 | def next_turn(turn): 129 | """Switch turns.""" 130 | if turn == X: 131 | return O 132 | else: 133 | return X 134 | 135 | def congrat_winner(the_winner, computer, human): 136 | """Congratulate the winner.""" 137 | if the_winner != TIE: 138 | print(the_winner, "won!\n") 139 | else: 140 | print("It's a tie!\n") 141 | 142 | if the_winner == computer: 143 | print("As I predicted, human, I am triumphant once more. \n" \ 144 | "Proof that computers are superior to humans in all regards.") 145 | elif the_winner == human: 146 | print("No, no! It cannot be! Somehow you tricked me, human. \n" \ 147 | "But never again! I, the computer, so swear it!") 148 | else: 149 | print("You were most lucky, human, and somehow managed to tie me. \n" \ 150 | "Celebrate today... for this is the best you will ever achieve.") 151 | 152 | if __name__ == '__main__': 153 | display_instruct() 154 | computer, human = pieces() # 'x', 'o' or 'o', 'x' 155 | turn = X 156 | board = ['0', '1', '2', '3', '4', '5', '6', '7', '8'] 157 | display_board(board) 158 | 159 | while not winner(board): 160 | if turn == human: 161 | move = human_move(board, human) 162 | board[move] = human 163 | else: 164 | move = computer_move(board, computer, human) 165 | board[move] = computer 166 | display_board(board) 167 | turn = next_turn(turn) 168 | 169 | the_winner = winner(board) 170 | congrat_winner(the_winner, computer, human) 171 | input("\n\nPress the enter key to quit.") 172 | --------------------------------------------------------------------------------