{"id":19776772,"url":"https://github.com/hafez-cs/python-handbook","last_synced_at":"2026-05-17T19:33:20.999Z","repository":{"id":228008652,"uuid":"772922515","full_name":"Hafez-CS/Python-Handbook","owner":"Hafez-CS","description":"Welcome to my python handbook! This handbook is a complete collection of Python tips and topics in a \"learning by example\" approach and I hope it is useful.","archived":false,"fork":false,"pushed_at":"2024-11-22T09:57:51.000Z","size":1617,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-29T04:26:03.355Z","etag":null,"topics":["handbook","python","python-handbook","reference"],"latest_commit_sha":null,"homepage":"https://github.com/Hafez-CS/Python-Handbook","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Hafez-CS.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-03-16T08:46:17.000Z","updated_at":"2025-10-25T07:14:06.000Z","dependencies_parsed_at":"2024-03-23T08:27:05.701Z","dependency_job_id":"dd91ffce-16b2-48c5-9638-0f9cf209a683","html_url":"https://github.com/Hafez-CS/Python-Handbook","commit_stats":null,"previous_names":["hafez-cs/python"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Hafez-CS/Python-Handbook","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Hafez-CS%2FPython-Handbook","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Hafez-CS%2FPython-Handbook/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Hafez-CS%2FPython-Handbook/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Hafez-CS%2FPython-Handbook/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Hafez-CS","download_url":"https://codeload.github.com/Hafez-CS/Python-Handbook/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Hafez-CS%2FPython-Handbook/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33151757,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-17T09:28:26.183Z","status":"ssl_error","status_checked_at":"2026-05-17T09:27:52.702Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["handbook","python","python-handbook","reference"],"created_at":"2024-11-12T05:21:43.444Z","updated_at":"2026-05-17T19:33:20.978Z","avatar_url":"https://github.com/Hafez-CS.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"Python Handbook\n===============================\n![Monty Python](https://cdn.dribbble.com/users/330915/screenshots/3587000/10_coding_dribbble.gif)\n\nIntroduction\n--------\n**Welcome to my python handbook!\nThis handbook is a complete collection of Python tips and topics in a \"learning by example\" approach and I hope it is useful.**\n\n### What is Python?\n**Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.**\n**It is used for:\nweb development (server-side),\nsoftware development,\nmathematics,\nsystem scripting.**\n\n### What can Python do?\n**Python can be used on a server to create web applications.\nPython can be used alongside software to create workflows.\nPython can connect to database systems. It can also read and modify files.\nPython can be used to handle big data and perform complex mathematics.\nPython can be used for rapid prototyping, or for production-ready software development.**\n\n### Why Python?\n**Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).\nPython has a simple syntax similar to the English language.\nPython has syntax that allows developers to write programs with fewer lines than some other programming languages.\nPython runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.\nPython can be treated in a procedural way, an object-oriented way or a functional way.**\n\n### good to know!\n**Python : https://www.python.org/**\n\n**Python packages : https://pypi.org/**\n\n**The Python Standard Library : https://docs.python.org/3/library/index.html**\n\n**VS Code : https://code.visualstudio.com/**\n\n**Learn more about python : https://www.w3schools.com/python/default.asp**\n\n**Learn more about python : https://www.geeksforgeeks.org/python-programming-language/**\n\n**Learn more about python : https://realpython.com/**\n\n\n\nContents\n--------\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **1. Home :** **\u0026nbsp;**  **[`Home`](#home)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **2. Variables :** **\u0026nbsp;**  **[`Variables`](#variables)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **3. Data Types :** **\u0026nbsp;**  **[`Data-Types`](#data-types)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **4. Numbers :** **\u0026nbsp;**  **[`Numbers`](#numbers)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **5. Strings :** **\u0026nbsp;**  **[`Strings`](#strings)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **6. Booleans :** **\u0026nbsp;**  **[`Booleans`](#booleans)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **7. Operators :** **\u0026nbsp;**  **[`Operators`](#operators)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **8. Lists :** **\u0026nbsp;**  **[`Lists`](#lists)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **9. Tuples :** **\u0026nbsp;**  **[`Tuples`](#tuples)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **10. Sets :** **\u0026nbsp;**  **[`Sets`](#sets)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **11. Dictionaries :** **\u0026nbsp;**  **[`Dictionaries`](#dictionaries)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **12. if-else :** **\u0026nbsp;**  **[`if-else`](#if-else)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **13. While Loops :** **\u0026nbsp;**  **[`While-Loops`](#while-loops)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **14. for Loops :** **\u0026nbsp;**  **[`for-Loops`](#for-loops)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **15. Functions :** **\u0026nbsp;**  **[`Functions`](#functions)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **16. lambda :** **\u0026nbsp;**  **[`lambda`](#lambda)** \n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **17. iterators :** **\u0026nbsp;**  **[`iterators`](#iterators)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **18. make my library :** **\u0026nbsp;**  **[`make-my-library`](#make-my-library)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **19. Datetime :** **\u0026nbsp;**  **[`Datetime`](#datetime)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;** **20. Math :** **\u0026nbsp;**  **[`Math`](#math)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **21. JSON :** **\u0026nbsp;**  **[`JSON`](#json)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **22. RegEx :** **\u0026nbsp;**  **[`RegEx`](#regex)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **23. Try-Except :** **\u0026nbsp;**  **[`Try-Except`](#try-except)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **24. Input :** **\u0026nbsp;**  **[`Input`](#input)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **25. String Formatting :** **\u0026nbsp;**  **[`String-Formatting`](#string-formatting)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **26. File Handling :** **\u0026nbsp;**  **[`File-Handling`](#file-handling)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **27. Built In Functions :** **\u0026nbsp;**  **[`Built-In-Functions`](#built-in-functions)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **28. Python Error :** **\u0026nbsp;**  **[`Python-Error`](#python-error)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **29. Random :** **\u0026nbsp;**  **[`Random`](#random)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **30. Enum :** **\u0026nbsp;**  **[`Enum`](#enum)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **31. System :** **\u0026nbsp;**  **[`System`](#system)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **32. Path :** **\u0026nbsp;**  **[`Path`](#path)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **33. Pickle :** **\u0026nbsp;**  **[`Pickle`](#pickle)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **34. Collections :** **\u0026nbsp;**  **[`Collections`](#collections)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **35. Operator :** **\u0026nbsp;**  **[`Operator`](#operator)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **36. Progress Bar :** **\u0026nbsp;**  **[`Progress-Bar`](#progress-bar)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **37. Matplotlib(chart) :** **\u0026nbsp;**  **[`Matplotlib`](#matplotlib)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **38. Table(tabulate) :** **\u0026nbsp;**  **[`Table`](#table)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **39. OOP(Class) :** **\u0026nbsp;**  **[`Class`](#class)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **40. CSV :** **\u0026nbsp;**  **[`CSV`](#csv)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **41. txt :** **\u0026nbsp;**  **[`txt`](#txt)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **42. OS :** **\u0026nbsp;**  **[`OS`](#os)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **43. MySQL :** **\u0026nbsp;**  **[`MySQL`](#mysql)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **44. Restrictions on Input :** **\u0026nbsp;**  **[`Restrictions-on-Input`](#restrictions-on-input)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **45. excel :** **\u0026nbsp;**  **[`excel`](#excel)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **46. PDF :** **\u0026nbsp;**  **[`PDF`](#pdf)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **47. Word :** **\u0026nbsp;**  **[`Word`](#word)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **48. Time :** **\u0026nbsp;**  **[`Time`](#time)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **49. Picture :** **\u0026nbsp;**  **[`Picture`](#picture)**\n\n**\u0026nbsp;\u0026nbsp;\u0026nbsp;**  **50. controlling-the-keyboard-and-mouse-with-GUI-automation :** **\u0026nbsp;**  **[`controlling-the-keyboard-and-mouse-with-GUI-automation`](#controlling-the-keyboard-and-mouse-with-GUI-automation)**\n\n\n\nHome\n----\n```python\nprint(\"Hello, World!\")\n\u003e\u003e \"Hello, World!\"\n\n# hello world\n```\n\n\nVariables\n----\n![Monty Python](https://files.realpython.com/media/Variables-in-Python_Watermarked.3868fbf92e1d.jpg)\n```python\nx = 5\ny = \"John\"\nprint(x)\nprint(y)\n\u003e\u003e 5\n\u003e\u003e \"John\"\n```\n\n```python\nx = 4       # x is of type int\nx = \"Sally\" # x is now of type str\nprint(x)\n\u003e\u003e \"Sally\"\n\n```\n\n```python\nx = str(3)    # x will be '3'\ny = int(3)    # y will be 3\nz = float(3)  # z will be 3.0\n```\n\n```python\nx = 5\ny = \"John\"\nprint(type(x))\nprint(type(y))\n\u003e\u003e \u003cclass 'int'\u003e\n\u003e\u003e \u003cclass 'str'\u003e\n```\n\n```python\nx, y, z = \"Orange\", \"Banana\", \"Cherry\"\nprint(x)\nprint(y)\nprint(z)\n\u003e\u003e \"Orange\"\n\u003e\u003e \"Banana\"\n\u003e\u003e \"Cherry\"\n```\n\n```python\nx = y = z = \"Orange\"\nprint(x)\nprint(y)\nprint(z)\n\u003e\u003e \"Orange\"\n\u003e\u003e \"Orange\"\n\u003e\u003e \"Orange\"\n```\n\n```python\nfruits = [\"apple\", \"banana\", \"cherry\"]\nx, y, z = fruits\nprint(x)\nprint(y)\nprint(z)\n\u003e\u003e [\"apple\", \"banana\", \"cherry\"]\n\u003e\u003e [\"apple\", \"banana\", \"cherry\"]\n\u003e\u003e [\"apple\", \"banana\", \"cherry\"]\n```\n\n```python\nx = \"Python is awesome\"\nprint(x)\n\u003e\u003e \"Python is awesome\"\n```\n\n```python\nx = \"Python\"\ny = \"is\"\nz = \"awesome\"\nprint(x, y, z)\n\u003e\u003e \"Python\" , \"is\" , \"awesome\"\n```\n\n```python\nx = \"Python \"\ny = \"is \"\nz = \"awesome\"\nprint(x + y + z)\n\u003e\u003e \"Python is awesome\"\n```\n\n```python\nx = 5\ny = 10\nprint(x + y)\n\u003e\u003e 15\n```\n\n\nData-Types\n----------\n![Monty Python](https://files.realpython.com/media/Basic-Data-Types-in-Python_Watermarked.e3dd34457952.jpg)\n* **Text Type :\tstr**\n* **Numeric Types :\tint, float, complex**\n* **Sequence Types :\tlist, tuple, range**\n* **Mapping Type :\tdict**\n* **Set Types :\tset, frozenset**\n* **Boolean Type :\tbool**\n* **Binary Types :\tbytes, bytearray, memoryview**\n* **None Type :\tNoneType**\n\n```python\nx = \"Hello World\"\t                              # str\t\nx = 20\t                                          # int\t\nx = 20.5\t                                      # float\t\nx = 1j\t                                          # complex\t\nx = [\"apple\", \"banana\", \"cherry\"]\t              # list\t\nx = (\"apple\", \"banana\", \"cherry\")\t              # tuple\t\nx = range(6)\t                                  # range\t\nx = {\"name\" : \"John\", \"age\" : 36}  \t              # dict\t\nx = {\"apple\", \"banana\", \"cherry\"}\t              # set\t\nx = frozenset({\"apple\", \"banana\", \"cherry\"})\t  # frozenset\t\nx = True\t                                      # bool\t\nx = b\"Hello\"\t                                  # bytes\t\nx = bytearray(5)\t                              # bytearray\t\nx = memoryview(bytes(5))\t                      # memoryview\t\nx = None\t                                      # NoneType\n```\n\n```python\nx = str(\"Hello World\")\t                        # str\t\nx = int(20)\t                                    # int\t\nx = float(20.5)\t                                # float\t\nx = complex(1j)\t                                # complex\t\nx = list((\"apple\", \"banana\", \"cherry\"))\t        # list\t\nx = tuple((\"apple\", \"banana\", \"cherry\"))\t    # tuple\t\nx = range(6)\t                                # range\t\nx = dict(name=\"John\", age=36)\t                # dict\t\nx = set((\"apple\", \"banana\", \"cherry\"))\t        # set\t\nx = frozenset((\"apple\", \"banana\", \"cherry\"))\t# frozenset\t\nx = bool(5)\t                                    # bool\t\nx = bytes(5)\t                                # bytes\t\nx = bytearray(5)\t                            # bytearray\t\nx = memoryview(bytes(5))\t                    # memoryview\n```\n\n\nNumbers\n---\n![Monty Python](https://files.realpython.com/media/Python-Basics-Chapter-Numbers-in-Python_Watermarked.70cee8925cbf.jpg)\n```python\nx = 1    # int\ny = 2.8  # float\nz = 1j   # complex\n```\n\n```python\nx = 1\ny = 35656222554887711\nz = -3255522\n```\n\n```python\nx = 1.10\ny = 1.0\nz = -35.59\n```\n\n```python\nx = int(1)   # x will be 1\ny = int(2.8) # y will be 2\nz = int(\"3\") # z will be 3\n```\n\n```python\nx = float(1)     # x will be 1.0\ny = float(2.8)   # y will be 2.8\nz = float(\"3\")   # z will be 3.0\nw = float(\"4.2\") # w will be 4.2\n```\n\n```python\nx = str(\"s1\") # x will be 's1'\ny = str(2)    # y will be '2'\nz = str(3.0)  # z will be '3.0'\n```\n\n\nStrings\n-----\n![Monty Python](https://files.realpython.com/media/Strings-and-Character-Data-in-Python_Watermarked.797803948b10.jpg)\n```python\na = \"Hello\"\nprint(a)\n\u003e\u003e \"Hello\"\n```\n\n```python\na = \"Hello, World!\"\nprint(a[1])\n\u003e\u003e \"e\"\n```\n\n```python\nb = \"Hello, World!\"\nprint(b[2:5])\n\u003e\u003e \"llo\"\n```\n\n```python\na = \"Hello, World!\"\nprint(len(a))\n\u003e\u003e 13\n```\n\n```python\ntxt = \"The best things in life are free!\"\nprint(\"free\" in txt)\n\u003e\u003e True\n```\n\n```python\na = \"Hello, World!\"\nprint(a.upper())\n\u003e\u003e \"HELLO, WORLD!\"\n```\n\n```python\na = \"Hello, World!\"\nprint(a.lower())\n\u003e\u003e \"hello, world!\"\n```\n\n```python\na = \" Hello, World! \"\nprint(a.strip()) # returns \"Hello, World!\"\n\u003e\u003e \"Hello, World!\"\n```\n\n```python\na = \"Hello, World!\"\nprint(a.replace(\"H\", \"J\"))\n\u003e\u003e \"Jello, World!\"\n```\n\n```python\na = \"Hello, World!\"\nprint(a.split(\",\")) # returns ['Hello', ' World!']\n\u003e\u003e \"['Hello', ' World!']\"\n```\n\n```python\na = \"Hello\"\nb = \"World\"\nc = a + b\nprint(c)\n\u003e\u003e \"HelloWorld\"\n```\n\n```python\na = \"Hello\"\nb = \"World\"\nc = a + \" \" + b\nprint(c)\n\u003e\u003e \"Hello World\"\n```\n\n```python\nage = 36\ntxt = \"My name is John, I am \" + age\nprint(txt)\n\u003e\u003e \"My name is John, I am 36\"\n```\n\n```python\nage = 36\ntxt = \"My name is John, and I am {}\"\nprint(txt.format(age))\n\u003e\u003e \"My name is John, I am 36\"\n```\n\n```python\nprint('G','F', sep='', end='')\nprint('G')\n\u003e\u003e \"GFG\"\n```\n\n```python\nprint('09','12','2016', sep='-', end='\\n')\n\u003e\u003e \"09-12-2016\"\n```\n\n```python\nprint('Red','Green','Blue', sep=',', end='@')\nprint('geeksforgeeks')\n\u003e\u003e \"Red,Green,Blue@geeksforgeeks\"\n```\n\n```python\nprint(\"Geeks : %2d, Portal : %5.2f\" % (1, 05.333)) \n\u003e\u003e \"Geeks :  1, Portal : 5.33\"\n ```\n\n```python\nprint(\"Total students : %3d, Boys : %2d\" % (240, 120))   # print integer value\n\u003e\u003e \"Total students : 240, Boys : 120\"\n ```\n\n```python\nprint(\"%7.3o\" % (25))   # print octal value\n\u003e\u003e \"    031\"\n ```\n\n```python\nprint(\"%10.3E\" % (356.08977))   # print exponential value\n\u003e\u003e \"3.561E+02\"\n```\n\n```python\ntab = {'geeks': 4127, 'for': 4098, 'geek': 8637678}\nprint('Geeks: {0[geeks]:d}; For: {0[for]:d}; '\n    'Geeks: {0[geek]:d}'.format(tab))\n\u003e\u003e \"Geeks: 4127; For: 4098; Geeks: 8637678\"\n```\n\n**`\"    \\'    \"` Single Quote**\n\n**`\"    \\\\    \"` Backslash**\n\n**`\"    \\n    \"` New Line**\n\n**`\"    \\r    \"` Carriage Return**\n\n**`\"    \\t    \"` Tab**\n\n**`\"    \\b    \"` Backspace**\n\n**`\"    \\f    \"` Form Feed**\n\n**`\"    \\ooo    \"` Octal value**\n\n**`\"    \\xhh    \"` Hex value**\n\n### All string methods :\n**.capitalize() (Converts the first character to upper case)**\n```python\ntxt = \"hello, and welcome to my world.\"\nx = txt.capitalize()\nprint (x)\n\u003e\u003e \"Hello, and welcome to my world.\"\n```\n\n**.casefold() (Converts string into lower case)**\n```python\ntxt = \"Hello, And Welcome To My World!\"\nx = txt.casefold()\nprint(x)\n\u003e\u003e \"hello, and welcome to my world!\"\n```\n\n**.center() (Returns a centered string)**\n```python\ntxt = \"banana\"\nx = txt.center(20)\nprint(x)\n\u003e\u003e \"       banana       \"\n```\n\n**.count() (Returns the number of times a specified value occurs in a string)**\n```python\ntxt = \"I love apples, apple are my favorite fruit\"\nx = txt.count(\"apple\")\nprint(x)\n\u003e\u003e 2\n```\n\n**.encode() (Returns an encoded version of the string)**\n```python\ntxt = \"My name is Ståle\"\nx = txt.encode()\nprint(x)\n\u003e\u003e b'My name is St\\xc3\\xa5le'\n```\n\n**.endswith() (Returns true if the string ends with the specified value)**\n```python\ntxt = \"Hello, welcome to my world.\"\nx = txt.endswith(\".\")\nprint(x)\n\u003e\u003e True\n```\n\n**.expandtabs() (Sets the tab size of the string)**\n```python\ntxt = \"H\\te\\tl\\tl\\to\"\nx =  txt.expandtabs(2)\nprint(x)\n\u003e\u003e \"H e l l o\"\n```\n\n**.find() (Searches the string for a specified value and returns the position of where it was found)**\n```python\ntxt = \"Hello, welcome to my world.\"\nx = txt.find(\"welcome\")\nprint(x)\n\u003e\u003e 7\n```\n\n**.format() (Formats specified values in a string)**\n```python\ntxt = \"For only {price:.2f} dollars!\"\nprint(txt.format(price = 49))\n\u003e\u003e \"For only 49.00 dollars!\"\n```\n\n**.index() (Searches the string for a specified value and returns the position of where it was found)**\n```python\ntxt = \"Hello, welcome to my world.\"\nx = txt.index(\"welcome\")\nprint(x)\n\u003e\u003e 7\n```\n\n**.isalnum() (Returns True if all characters in the string are alphanumeric)**\n```python\ntxt = \"Company12\"\nx = txt.isalnum()\nprint(x)\n\u003e\u003e True\n```\n\n**.isalpha() (Returns True if all characters in the string are in the alphabet)**\n```python\ntxt = \"CompanyX\"\nx = txt.isalpha()\nprint(x)\n\u003e\u003e True\n```\n\n**.isascii() (Returns True if all characters in the string are ascii characters)**\n```python\ntxt = \"Company123\"\nx = txt.isascii()\nprint(x)\n\u003e\u003e True\n```\n\n**.isdecimal() (Returns True if all characters in the string are decimals)**\n```python\ntxt = \"1234\"\nx = txt.isdecimal()\nprint(x)\n\u003e\u003e True\n```\n\n**.isdigit() (Returns True if all characters in the string are digits)**\n```python\ntxt = \"50800\"\nx = txt.isdigit()\nprint(x)\n\u003e\u003e True\n```\n\n**.isidentifier() (Returns True if the string is an identifier)**\n```python\ntxt = \"Demo\"\nx = txt.isidentifier()\nprint(x)\n\u003e\u003e True\n```\n\n**.islower() (Returns True if all characters in the string are lower case)**\n```python\ntxt = \"hello world!\"\nx = txt.islower()\nprint(x)\n\u003e\u003e True\n```\n\n**.isnumeric() (Returns True if all characters in the string are numeric)**\n```python\ntxt = \"565543\"\nx = txt.isnumeric()\nprint(x)\n\u003e\u003e True\n```\n\n**.isprintable() (Returns True if all characters in the string are printable)**\n```python\ntxt = \"Hello! Are you #1?\"\nx = txt.isprintable()\nprint(x)\n\u003e\u003e True\n```\n\n**.isspace() (Returns True if all characters in the string are whitespaces)**\n```python\ntxt = \"   \"\nx = txt.isspace()\nprint(x)\n\u003e\u003e True\n```\n\n**.istitle() (Returns True if the string follows the rules of a title)**\n```python\ntxt = \"Hello, And Welcome To My World!\"\nx = txt.istitle()\nprint(x)\n\u003e\u003e True\n```\n\n**.isupper() (Returns True if all characters in the string are upper case)**\n```python\ntxt = \"THIS IS NOW!\"\nx = txt.isupper()\nprint(x)\n\u003e\u003e True\n```\n\n**.join() (Joins the elements of an iterable to the end of the string)**\n```python\nmyTuple = (\"John\", \"Peter\", \"Vicky\")\nx = \"#\".join(myTuple)\nprint(x)\n\u003e\u003e \"John#Peter#Vicky\"\n```\n\n**.ljust() (Returns a left justified version of the string)**\n```python\ntxt = \"banana\"\nx = txt.ljust(20)\nprint(x, \"is my favorite fruit.\")\n\u003e\u003e \"banana               is my favorite fruit.\"\n```\n\n**.lower() (Converts a string into lower case)**\n```python\ntxt = \"Hello my FRIENDS\"\nx = txt.lower()\nprint(x)\n\u003e\u003e \"hello my friends\"\n```\n\n**.lstrip() (Returns a left trim version of the string)**\n```python\ntxt = \"     banana     \"\nx = txt.lstrip()\nprint(\"of all fruits\", x, \"is my favorite\")\n\u003e\u003e \"of all fruits banana      is my favorite\"\n```\n\n**.maketrans() (Returns a translation table to be used in translations)**\n```python\ntxt = \"Hello Sam!\"\nmytable = str.maketrans(\"S\", \"P\")\nprint(txt.translate(mytable))\n\u003e\u003e \"Hello Pam!\"\n```\n\n**.partition() (Returns a tuple where the string is parted into three parts)**\n```python\ntxt = \"I could eat bananas all day\"\nx = txt.partition(\"bananas\")\nprint(x)\n\u003e\u003e ('I could eat ', 'bananas', ' all day')\n```\n\n**.replace() (Returns a string where a specified value is replaced with a specified value)**\n```python\ntxt = \"I like bananas\"\nx = txt.replace(\"bananas\", \"apples\")\nprint(x)\n\u003e\u003e \"I like apples\"\n```\n\n**.rfind() (Searches the string for a specified value and returns the last position of where it was found)**\n```python\ntxt = \"Mi casa, su casa.\"\nx = txt.rfind(\"casa\")\nprint(x)\n\u003e\u003e 12\n```\n\n**.rindex() (Searches the string for a specified value and returns the last position of where it was found)**\n```python\ntxt = \"Mi casa, su casa.\"\nx = txt.rindex(\"casa\")\nprint(x)\n\u003e\u003e 12\n```\n\n**.rjust() (Returns a right justified version of the string)**\n```python\ntxt = \"banana\"\nx = txt.rjust(20)\nprint(x, \"is my favorite fruit.\")\n\u003e\u003e \"              banana is my favorite fruit.\"\n```\n\n**.rpartition() (Returns a tuple where the string is parted into three parts)**\n```python\ntxt = \"I could eat bananas all day, bananas are my favorite fruit\"\nx = txt.rpartition(\"bananas\")\nprint(x)\n\u003e\u003e ('I could eat bananas all day, ', 'bananas', ' are my favorite fruit')\n```\n\n**.rsplit() (Splits the string at the specified separator, and returns a list)**\n```python\ntxt = \"apple, banana, cherry\"\nx = txt.rsplit(\", \")\nprint(x)\n\u003e\u003e ['apple', 'banana', 'cherry']\n```\n\n**.rstrip() (Returns a right trim version of the string)**\n```python\ntxt = \"     banana     \"\nx = txt.rstrip()\nprint(\"of all fruits\", x, \"is my favorite\")\n\u003e\u003e \"of all fruits      banana is my favorite\"\n```\n\n**.split() (Splits the string at the specified separator, and returns a list)**\n```python\ntxt = \"welcome to the jungle\"\nx = txt.split()\nprint(x)\n\u003e\u003e ['welcome', 'to', 'the', 'jungle']\n```\n\n**.splitlines() (Splits the string at line breaks and returns a list)**\n```python\ntxt = \"Thank you for the music\\nWelcome to the jungle\"\nx = txt.splitlines()\nprint(x)\n\u003e\u003e ['Thank you for the music', 'Welcome to the jungle']\n```\n\n**.startswith()             (Returns true if the string starts with the specified value)**\n```python\ntxt = \"Hello, welcome to my world.\"\nx = txt.startswith(\"Hello\")\nprint(x)\n\u003e\u003e True\n```\n\n**.strip() (Returns a trimmed version of the string)**\n```python\ntxt = \"     banana     \"\nx = txt.strip()\nprint(\"of all fruits\", x, \"is my favorite\")\n\u003e\u003e \"of all fruits banana is my favorite\"\n```\n\n**.swapcase() (Swaps cases, lower case becomes upper case and vice versa)**\n```python\ntxt = \"Hello My Name Is PETER\"\nx = txt.swapcase()\nprint(x)\n\u003e\u003e \"hELLO mY nAME iS peter\"\n```\n\n**.title() (Converts the first character of each word to upper case)**\n```python\ntxt = \"Welcome to my world\"\nx = txt.title()\nprint(x)\n\u003e\u003e \"Welcome To My World\"\n```\n\n**.translate() (Returns a translated string)**\n```python\nmydict = {83:  80}\ntxt = \"Hello Sam!\"\nprint(txt.translate(mydict))\n\u003e\u003e \"Hello Pam!\"\n```\n\n**.upper() (Converts a string into upper case)**\n```python\ntxt = \"Hello my friends\"\nx = txt.upper()\nprint(x)\n\u003e\u003e \"HELLO MY FRIENDS\"\n```\n\n**.zfill() (Fills the string with a specified number of 0 values at the beginning0**\n```python\ntxt = \"50\"\nx = txt.zfill(10)\nprint(x)\n\u003e\u003e 0000000050\n```\n\n\nBooleans\n-----\n![Monty Python](https://files.realpython.com/media/What-is-a-Python-Boolean_Watermarked.ba6413996cb3.jpg)\n```python\nprint(10 \u003e 9)\nprint(10 == 9)\nprint(10 \u003c 9)\n\u003e\u003e True\n\u003e\u003e False\n\u003e\u003e False\n```\n\n```python\nprint(bool(\"Hello\"))\nprint(bool(15))\n\u003e\u003e True\n\u003e\u003e True\n```\n\n\nOperators\n---------\n![Monty Python](https://files.realpython.com/media/Operators-and-Expressions-in-Python_Watermarked.651045da4031.jpg)\n**`2 + 2 = 4`**\n\n**`2 - 2 = 0`**\n\n**`2 * 3 = 6`**\n\n**`4 / 2 = 2`**\n\n**`4 % 2 = 0`**\n\n**`2 ** 3 = 8`**\n\n**`8 // 4 = 2`**\n\n**`2 == 2` 2 is equal to 2**\n\n**`2 != 3` 2 is not equal to 3**\n\n**`4 \u003e 2` 4 is greater than 2**\n\n**`2 \u003c 4` 2 smaller than 4**\n\n**`4 \u003e= 4` 4 bigger equals 4**\n\n**`4 \u003c= 4` 4 bigger equals 4**\n\n**`and` Returns True if both statements are true `x \u003c 5 and x \u003c 10`**\n\n**`or` Returns True if one of the statements is true `x \u003c 5 or x \u003c 4`**\n\n**`not` Reverse the result, returns False if the result is true `not(x \u003c 5 and x \u003c 10)`**\n\n**`in` Returns True if a sequence with the specified value is present in the object `x in y`**\n\n**`not in` Returns True if a sequence with the specified value is not present in the object `x not in y`**\n\n**`\u0026` AND\tSets each bit to 1 if both bits are 1 `x \u0026 y`**\n\n**`|` OR\tSets each bit to 1 if one of two bits is 1 `x | y`**\n\n**`^` XOR\tSets each bit to 1 if only one of two bits is 1 `x ^ y`**\n\n**`~` NOT\tInverts all the bits `~x`**\n\n**`\u003c\u003c` Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off `x \u003c\u003c 2`**\n\n**`\u003e\u003e` Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off `x \u003e\u003e 2`**\n\n\n\n**`x = 5` Or `x = 5`**\n\n**`x += 3` Or `x = x + 3`**\n\n**`x -= 3` Or `x = x - 3`**\n\n**`x *= 3` Or `x = x * 3`**\n\n**`x /= 3` Or `x = x / 3`**\n\n**`x %= 3` Or `x = x % 3`**\n\n**`x //= 3` Or `x = x // 3`**\n\n**`x **= 3` Or `x = x ** 3`**\n\n**`x \u0026= 3` Or `x = x \u0026 3`**\n\n**`x |= 3` Or `x = x | 3`**\n\n**`x ^= 3` Or `x = x ^ 3`**\n\n**`x \u003e\u003e= 3` Or `x = x \u003e\u003e 3`**\n\n**`x \u003c\u003c= 3` Or `x = x \u003c\u003c 3`**\n\n\nLists\n--------\n![Monty Python](https://files.realpython.com/media/Lists-and-Tuples-in-Python_Watermarked.4d655c81a78b.jpg)\n**Python's list is a flexible, versatile, powerful, and popular built-in data type. It allows you to create variable-length and mutable sequences of objects. In a list, you can store objects of any type. You can also mix objects of different types within the same list, although list elements often share the same type.**\n```python\nmylist = [\"apple\", \"banana\", \"cherry\"]\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nprint(thislist)\n\u003e\u003e ['apple', 'banana', 'cherry']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nprint(len(thislist))\n\u003e\u003e 3\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nprint(thislist[1])\n\u003e\u003e \"banana\"\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\", \"orange\", \"kiwi\", \"melon\", \"mango\"]\nprint(thislist[2:5])\n\u003e\u003e ['cherry', 'orange', 'kiwi']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nthislist[1:2] = [\"blackcurrant\", \"watermelon\"]\nprint(thislist)\n\u003e\u003e ['apple', 'blackcurrant', 'watermelon', 'cherry']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nthislist.insert(2, \"watermelon\")\nprint(thislist)\n\u003e\u003e ['apple', 'banana', 'watermelon', 'cherry']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nthislist.append(\"orange\")\nprint(thislist)\n\u003e\u003e ['apple', 'banana', 'cherry', 'orange']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\ntropical = [\"mango\", \"pineapple\", \"papaya\"]\nthislist.extend(tropical)\nprint(thislist)\n\u003e\u003e ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nthislist.remove(\"banana\")\nprint(thislist)\n\u003e\u003e ['apple', 'cherry']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nthislist.pop(1)\nprint(thislist)\n\u003e\u003e ['apple', 'cherry']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nthislist.pop()\nprint(thislist)\n\u003e\u003e ['apple', 'banana']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\ndel thislist[0]\nprint(thislist)\n\u003e\u003e ['banana', 'cherry']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\ndel thislist\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nthislist.clear()\nprint(thislist)\n\u003e\u003e []\n```\n\n```python\nthislist = [\"orange\", \"mango\", \"kiwi\", \"pineapple\", \"banana\"]\nthislist.sort()\nprint(thislist)\n\u003e\u003e ['banana', 'kiwi', 'mango', 'orange', 'pineapple']\n```\n\n```python\nthislist = [\"orange\", \"mango\", \"kiwi\", \"pineapple\", \"banana\"]\nthislist.sort(reverse = True)\nprint(thislist)\n\u003e\u003e ['pineapple', 'orange', 'mango', 'kiwi', 'banana']\n```\n\n```python\nthislist = [\"banana\", \"Orange\", \"Kiwi\", \"cherry\"]\nthislist.sort(key = str.lower)\nprint(thislist)\n\u003e\u003e ['banana', 'cherry', 'Kiwi', 'Orange']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nmylist = thislist.copy()\nprint(mylist)\n\u003e\u003e ['apple', 'banana', 'cherry']\n```\n\n```python\nthislist = [\"apple\", \"banana\", \"cherry\"]\nmylist = list(thislist)\nprint(mylist)\n\u003e\u003e ['apple', 'banana', 'cherry']\n```\n\n```python\nlist1 = [\"a\", \"b\", \"c\"]\nlist2 = [1, 2, 3]\nlist3 = list1 + list2\nprint(list3)\n\u003e\u003e ['a', 'b', 'c', 1, 2, 3]\n```\n\n```python\na = [0] * 6\nprint(a)\n\u003e\u003e [0, 0, 0, 0, 0, 0]\n```\n\n```python\n[1] * 7\n\u003e\u003e [1, 1, 1, 1, 1, 1, 1]\n```\n\n```python\na = [[]] * 10\nprint(a)\n\u003e\u003e [[], [], [], [], [], [], [], [], [], []]\n\na[5] += [2]\nprint(a)\n\u003e\u003e [[2], [2], [2], [2], [2], [2], [2], [2], [2], [2]]\n\na[0] = [3]\nprint(a)\n\u003e\u003e [[3], [2], [2], [2], [2], [2], [2], [2], [2], [2]]\n\na[1] += [3]\nprint(a)\n\u003e\u003e [[3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3], [2, 3]]\n```\n\n```python\nb = [[] for i in range(10)]\nprint(b)\n\u003e\u003e [[], [], [], [], [], [], [], [], [], []]\n\nb[5] += [2]\nprint(b)\n\u003e\u003e [[], [], [], [], [], [2], [], [], [], []]\n\nb[5] += [3]\nprint(b)\n\u003e\u003e [[], [], [], [], [], [2, 3], [], [], [], []]\n```\n\n```python\nb = [\n    [[1,2,3] , [] , [],\n     [] , [] , []] , \n    [[] , [] , [],\n     [] , [] , []] , \n    [[] , [] , [],\n     [] , [] , []] ,\n    [[] , [] , [],\n     [] , [] , []] , \n    [[] , [] , [],\n     [] , [] , []] , \n    [[] , [] , [],\n     [] , [] , []]\n]\n\nprint(b)\n\u003e\u003e [[[1, 2, 3], [], [], [], [], []], [[], [], [], [], [], []], [[], [], [], [], [], []], [[], [], [], [], [], []], [[], [], [], [], [], []], [[], [], [], [], [], []]]\n```\n\n### All List methods :\n**.append() (Adds an element at the end of the list)**\n```python\nfruits = ['apple', 'banana', 'cherry']\nfruits.append(\"orange\")\nprint(fruits)\n\u003e\u003e ['apple', 'banana', 'cherry', 'orange']\n```\n\n**.clear() (Removes all the elements from the list)**\n```python\nfruits = ['apple', 'banana', 'cherry', 'orange']\nfruits.clear()\nprint(fruits)\n\u003e\u003e []\n```\n\n**.copy() (Returns a copy of the list)**\n```python\nfruits = ['apple', 'banana', 'cherry', 'orange']\nx = fruits.copy()\nprint(x)\n\u003e\u003e ['apple', 'banana', 'cherry', 'orange']\n```\n\n**.count() (Returns the number of elements with the specified value)**\n```python\nfruits = ['apple', 'banana', 'cherry']\nx = fruits.count(\"cherry\")\nprint(x)\n\u003e\u003e 1\n```\n\n**.extend() (Add the elements of a list (or any iterable), to the end of the current list)**\n```python\nfruits = ['apple', 'banana', 'cherry']\ncars = ['Ford', 'BMW', 'Volvo']\nfruits.extend(cars)\nprint(fruits)\n\u003e\u003e ['apple', 'banana', 'cherry', 'Ford', 'BMW', 'Volvo']\n```\n\n**.index() (Returns the index of the first element with the specified value)**\n```python\nfruits = ['apple', 'banana', 'cherry']\nx = fruits.index(\"cherry\")\nprint(x)\n\u003e\u003e 2\n```\n\n**.insert() (Adds an element at the specified position)**\n```python\nfruits = ['apple', 'banana', 'cherry']\nfruits.insert(1, \"orange\")\nprint(fruits)\n\u003e\u003e ['apple', 'orange', 'banana', 'cherry']\n```\n\n**.pop() (Removes the element at the specified position)**\n```python\nfruits = ['apple', 'banana', 'cherry']\nfruits.pop(1)\nprint(fruits)\n\u003e\u003e ['apple', 'cherry']\n```\n\n**.remove() (Removes the item with the specified value)**\n```python\nfruits = ['apple', 'banana', 'cherry']\nfruits.remove(\"banana\")\nprint(fruits)\n\u003e\u003e ['apple', 'cherry']\n```\n\n**.reverse() (Reverses the order of the list)**\n```python\nfruits = ['apple', 'banana', 'cherry']\nfruits.reverse()\nprint(fruits)\n\u003e\u003e ['cherry', 'banana', 'apple']\n```\n\n**.sort() (Sorts the list)**\n```python\ncars = ['Ford', 'BMW', 'Volvo']\ncars.sort()\nprint(cars)\n\u003e\u003e ['BMW', 'Ford', 'Volvo']\n```\n\n\n\nTuples\n---------\n![Monty Python](https://files.realpython.com/media/Pythons-tuple-Built-in-Data-Type-A-Deep-Dive-with-Examples_Watermarked.e85efb14c955.jpg)\n**Python tuples are a type of data structure that is very similar to lists. The main difference between the two is that tuples are immutable, meaning they cannot be changed once they are created. This makes them ideal for storing data that should not be modified, such as database records.**\n* **`count()`\tReturns the number of times a specified value occurs in a tuple.**\n* **`index()`\tSearches the tuple for a specified value and returns the position of where it was found.**\n\n```python\nmytuple = (\"apple\", \"banana\", \"cherry\")\n```\n\n```python\nthistuple = (\"apple\", \"banana\", \"cherry\")\nprint(thistuple)\n\u003e\u003e ('apple', 'banana', 'cherry')\n```\n\n```python\nthistuple = (\"apple\", \"banana\", \"cherry\")\nprint(len(thistuple))\n\u003e\u003e 3\n```\n\n```python\nthistuple = (\"apple\", \"banana\", \"cherry\")\nprint(thistuple[1])\n\u003e\u003e \"banana\"\n```\n\n```python\nthistuple = (\"apple\", \"banana\", \"cherry\")\ny = list(thistuple)\ny.remove(\"apple\")\nthistuple = tuple(y)\nprint(thistuple)\n\u003e\u003e ('banana', 'cherry')\n```\n\n```python\nthistuple = (\"apple\", \"banana\", \"cherry\")\ndel thistuple\nprint(thistuple)\n\u003e\u003e Error\n```\n\n```python\ntuple1 = (\"a\", \"b\" , \"c\")\ntuple2 = (1, 2, 3)\ntuple3 = tuple1 + tuple2\nprint(tuple3)\n\u003e\u003e ('a', 'b', 'c', 1, 2, 3)\n```\n\n\nSets\n----\n![Monty Python](https://files.realpython.com/media/Sets-in-Python_Watermarked.cd8d2e9563c3.jpg)\n**A set is a data collection type used in Python for storing multiple items in a single variable. Sets in Python are unordered and, as such, are not always consistent in the order they get returned. Furthermore, items in the set are immutable — ie. cannot be changed.**\n```python\nmyset = {\"apple\", \"banana\", \"cherry\"}\n```\n\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\nprint(thisset)\n\u003e\u003e {'cherry', 'banana', 'apple'}\n```\n\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\nprint(len(thisset))\n\u003e\u003e 3\n```\n\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\nthisset.add(\"orange\")\nprint(thisset)\n\u003e\u003e {'cherry', 'apple', 'banana', 'orange'}\n```\n\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\ntropical = {\"pineapple\", \"mango\", \"papaya\"}\nthisset.update(tropical)\nprint(thisset)\n\u003e\u003e {'papaya', 'mango', 'pineapple', 'apple', 'banana', 'cherry'}\n```\n\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\nthisset.remove(\"banana\")\nprint(thisset)\n\u003e\u003e {'cherry', 'apple'}\n```\n\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\nthisset.discard(\"banana\")\nprint(thisset)\n\u003e\u003e {'cherry', 'apple'}\n```\n\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\nx = thisset.pop()\nprint(x)\n\u003e\u003e \"cherry\"\nprint(thisset)\n\u003e\u003e {'apple', 'banana'}\n```\n\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\nx = thisset.pop()\nprint(x)\n\u003e\u003e \"cherry\"\nprint(thisset)\n\u003e\u003e {'apple', 'banana'}\n```\n\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\nthisset.clear()\nprint(thisset)\n\u003e\u003e ()\n```\n\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\ndel thisset\nprint(thisset)\n\u003e\u003e Error\n```\n\n```python\nset1 = {\"a\", \"b\" , \"c\"}\nset2 = {1, 2, 3}\nset3 = set1.union(set2)\nprint(set3)\n\u003e\u003e {1, 'c', 2, 3, 'a', 'b'}\n```\n\n```python\nset1 = {\"a\", \"b\" , \"c\"}\nset2 = {1, 2, 3}\nset1.update(set2)\nprint(set1)\n\u003e\u003e {1, 'c', 2, 3, 'a', 'b'}\n```\n\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"apple\"}\nx.intersection_update(y)\nprint(x)\n\u003e\u003e {'apple'}\n```\n\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"apple\"}\nz = x.intersection(y)\nprint(z)\n\u003e\u003e {'apple'}\n```\n\n### All Sets methods :\n**.add() (Adds an element to the set)**\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\nthisset.add(\"orange\")\nprint(thisset)\n\u003e\u003e {'cherry', 'orange', 'apple', 'banana'}\n```\n\n**.clear() (Removes all the elements from the set)**\n```python\nfruits = {\"apple\", \"banana\", \"cherry\"}\nfruits.clear()\nprint(fruits)\n\u003e\u003e set()\n```\n\n**.copy() (Returns a copy of the set)**\n```python\nfruits = {\"apple\", \"banana\", \"cherry\"}\nx = fruits.copy()\nprint(x)\n\u003e\u003e {'apple', 'cherry', 'banana'}\n```\n\n**.difference() (Returns a set containing the difference between two or more sets)**\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"apple\"}\nz = x.difference(y)\nprint(z)\n\u003e\u003e {'cherry', 'banana'}\n```\n\n**.difference_update() (Removes the items in this set that are also included in another, specified set)**\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"apple\"}\nx.difference_update(y)\nprint(x)\n\u003e\u003e {'cherry', 'banana'}\n```\n\n**.discard()(Remove the specified item)**\n```python\nthisset = {\"apple\", \"banana\", \"cherry\"}\nthisset.discard(\"banana\")\nprint(thisset)\n\u003e\u003e {'apple', 'cherry'}\n```\n\n**.intersection() (Returns a set, that is the intersection of two other sets)**\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"apple\"}\nz = x.intersection(y)\nprint(z)\n\u003e\u003e {'apple'}\n```\n\n**.intersection_update() (Removes the items in this set that are not present in other, specified set(s))**\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"apple\"}\nx.intersection_update(y) \nprint(x)\n\u003e\u003e {'apple'}\n```\n\n**.isdisjoint() (Returns whether two sets have a intersection or not)**\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"facebook\"}\nz = x.isdisjoint(y) \nprint(z)\n\u003e\u003e True\n```\n\n**.issubset() (Returns whether another set contains this set or not)**\n```python\nx = {\"a\", \"b\", \"c\"}\ny = {\"f\", \"e\", \"d\", \"c\", \"b\", \"a\"}\nz = x.issubset(y)\nprint(z)\n\u003e\u003e True\n```\n\n**.issuperset() (Returns whether this set contains another set or not)**\n```python\nx = {\"f\", \"e\", \"d\", \"c\", \"b\", \"a\"}\ny = {\"a\", \"b\", \"c\"}\nz = x.issuperset(y) \nprint(z)\n\u003e\u003e True\n```\n\n**.pop() (Removes an element from the set)**\n```python\nfruits = {\"apple\", \"banana\", \"cherry\"}\nfruits.pop() \nprint(fruits)\n\u003e\u003e {'banana', 'cherry'}\n```\n\n**.remove() (Removes the specified element)**\n```python\nfruits = {\"apple\", \"banana\", \"cherry\"}\nfruits.remove(\"banana\") \nprint(fruits)\n\u003e\u003e {'cherry', 'apple'}\n```\n\n**.symmetric_difference() (Returns a set with the symmetric differences of two sets)**\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"apple\"}\nz = x.symmetric_difference(y)\nprint(z)\n\u003e\u003e {'cherry', 'microsoft', 'banana', 'google'}\n```\n\n**.symmetric_difference_update() (inserts the symmetric differences from this set and another)**\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"apple\"}\nx.symmetric_difference_update(y)\nprint(x)\n\u003e\u003e {'google', 'microsoft', 'banana', 'cherry'}\n```\n\n**.union() (Return a set containing the union of sets)**\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"apple\"}\nz = x.union(y)\nprint(z)\n\u003e\u003e {'apple', 'microsoft', 'cherry', 'banana', 'google'}\n```\n\n**.update() (Update the set with the union of this set and others)**\n```python\nx = {\"apple\", \"banana\", \"cherry\"}\ny = {\"google\", \"microsoft\", \"apple\"}\nx.update(y) \nprint(x)\n\u003e\u003e {'cherry', 'microsoft', 'banana', 'apple', 'google'}\n```\n\nDictionaries\n------\n![Monty Python](https://files.realpython.com/media/Dictionaries-in-Python_Watermarked.3656a2293c00.jpg)\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nprint(thisdict)\n\u003e\u003e {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nprint(thisdict[\"brand\"])\n\u003e\u003e \"Ford\"\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nprint(len(thisdict))\n\u003e\u003e 3\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"electric\": False,\n  \"year\": 1964,\n  \"colors\": [\"red\", \"white\", \"blue\"]\n}\n```\n\n```python\nthisdict = dict(name = \"John\", age = 36, country = \"Norway\")\nprint(thisdict)\n\u003e\u003e {'name': 'John', 'age': 36, 'country': 'Norway'}\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nx = thisdict.get(\"model\")\n\u003e\u003e \"Mustang\"\nx = thisdict[\"model\"]\n\u003e\u003e \"Mustang\"\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nprint(thisdict.keys())\n\u003e\u003e dict_keys(['brand', 'model', 'year'])\n```\n\n```python\ncar = {\n\"brand\": \"Ford\",\n\"model\": \"Mustang\",\n\"year\": 1964\n}\n```\n\n```python\nthisdict = {\n\"brand\": \"Ford\",\n\"model\": \"Mustang\",\n\"year\": 1964\n}\nprint(thisdict.values())\n\u003e\u003e dict_values(['Ford', 'Mustang', 1964])\n```\n\n```python\nthisdict = {\n\"brand\": \"Ford\",\n\"model\": \"Mustang\",\n\"year\": 1964\n}\nprint(thisdict.items())\n\u003e\u003e dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nthisdict[\"year\"] = 2018\n\n# Or\n\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nthisdict.update({\"year\": 2020})\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nthisdict[\"color\"] = \"red\"\nprint(thisdict)\n\u003e\u003e {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}\n\n# or\n\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nthisdict.update({\"color\": \"red\"})\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nthisdict.pop(\"model\")\nprint(thisdict)\n\u003e\u003e {'brand': 'Ford', 'year': 1964}\n\n# or\n\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nthisdict.popitem()\nprint(thisdict)\n\u003e\u003e {'brand': 'Ford', 'model': 'Mustang'}\n\n# or\n\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\ndel thisdict[\"model\"]\nprint(thisdict)\n\u003e\u003e {'brand': 'Ford', 'year': 1964}\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nthisdict.clear()\nprint(thisdict)\n\u003e\u003e {}\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nfor x in thisdict.values():\n  print(x)\n\u003e\u003e \"Ford\"\n   \"Mustang\"\n   1964\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nfor x in thisdict.keys():\n  print(x)\n\u003e\u003e \"brand\"\n   \"model\"\n   \"year\"\n```\n\n```python\nthisdict = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nmydict = thisdict.copy()\nprint(mydict)\n\u003e\u003e {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}\n```\n\n```python\nmyfamily = {\n  \"child1\" : {\n    \"name\" : \"Emil\",\n    \"year\" : 2004\n  },\n  \"child2\" : {\n    \"name\" : \"Tobias\",\n    \"year\" : 2007\n  },\n  \"child3\" : {\n    \"name\" : \"Linus\",\n    \"year\" : 2011\n  }\n}\n```\n\n### All Dictionaries methods :\n**.clear() (Removes all the elements from the dictionary)**\n```python\ncar =\t{\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\ncar.clear()\nprint(car)\n\u003e\u003e {}\n```\n\n**.copy() (Returns a copy of the dictionary)**\n```python\ncar = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nx = car.copy()\nprint(x)\n\u003e\u003e {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}\n```\n\n**.fromkeys() (Returns a dictionary with the specified keys and value)**\n```python\nx = ('key1', 'key2', 'key3')\ny = 0\nthisdict = dict.fromkeys(x, y)\nprint(thisdict)\n\u003e\u003e {'key1': 0, 'key2': 0, 'key3': 0}\n```\n\n**.get() (Returns the value of the specified key)**\n```python\ncar = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nx = car.get(\"model\")\nprint(x)\n\u003e\u003e \"Mustang\"\n```\n\n**.items() (Returns a list containing a tuple for each key value pair)**\n```python\ncar = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nx = car.items()\nprint(x)\n\u003e\u003e dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])\n```\n\n**.keys() (Returns a list containing the dictionary's keys)**\n```python\ncar = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nx = car.keys()\nprint(x)\n\u003e\u003e dict_keys(['brand', 'model', 'year'])\n```\n\n**.pop() (Removes the element with the specified key)**\n```python\ncar = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\ncar.pop(\"model\")\nprint(car)\n\u003e\u003e {'brand': 'Ford', 'year': 1964}\n```\n\n**.popitem() (Removes the last inserted key-value pair)**\n```python\ncar = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\ncar.popitem()\nprint(car)\n\u003e\u003e {'brand': 'Ford', 'model': 'Mustang'}\n```\n\n**.setdefault() (Returns the value of the specified key. If the key does not exist: insert the key, with the specified value)**\n```python\ncar = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nx = car.setdefault(\"model\", \"Bronco\")\nprint(x)\n\u003e\u003e \"Mustang\"\n```\n\n**.update() (Updates the dictionary with the specified key-value pairs)**\n```python\ncar = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\ncar.update({\"color\": \"White\"})\nprint(car)\n\u003e\u003e {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}\n```\n\n**.values() (Returns a list of all the values in the dictionary)**\n```python\ncar = {\n  \"brand\": \"Ford\",\n  \"model\": \"Mustang\",\n  \"year\": 1964\n}\nx = car.values()\nprint(x)\n\u003e\u003e dict_values(['Ford', 'Mustang', 1964])\n```\n\n\nif-else\n-----\n![Monty Python](https://files.realpython.com/media/Conditional-Statements-in-Python_Watermarked.b6b7d30ff62b.jpg)\n* **Equals : `a == b`**\n* **Not Equals : `a != b`**\n* **Less than : `a \u003c b`**\n* **Less than or equal to : `a \u003c= b`**\n* **Greater than : `a \u003e b`**\n* **Greater than or equal to : `a \u003e= b`**\n\n```python\na = 33\nb = 200\nif b \u003e a:\n  print(\"b is greater than a\")\n\u003e\u003e \"b is greater than a\"\n```\n\n```python\na = 33\nb = 33\nif b \u003e a:\n  print(\"b is greater than a\")\nelif a == b:\n  print(\"a and b are equal\")\n\u003e\u003e \"a and b are equal\"\n```\n\n```python\na = 200\nb = 33\nif b \u003e a:\n  print(\"b is greater than a\")\nelif a == b:\n  print(\"a and b are equal\")\nelse:\n  print(\"a is greater than b\")\n\u003e\u003e \"a is greater than b\"\n```\n\n```python\na = 200\nb = 33\nif b \u003e a:\n  print(\"b is greater than a\")\nelse:\n  print(\"b is not greater than a\")\n\u003e\u003e \"b is not greater than a\"\n```\n\n```python\na = 200\nb = 100\nif a \u003e b: print(\"a is greater than b\")\n\u003e\u003e \"a is greater than b\"\n```\n\n```python\na = 2\nb = 330\nprint(\"A\") if a \u003e b else print(\"B\")\n\u003e\u003e \"B\"\n```\n\n```python\na = 330\nb = 330\nprint(\"A\") if a \u003e b else print(\"=\") if a == b else print(\"B\")\n\u003e\u003e \"=\"\n```\n\n```python\na = 200\nb = 33\nc = 500\nif a \u003e b and c \u003e a:\n  print(\"Both conditions are True\")\n\u003e\u003e \"Both conditions are True\"\n```\n\n```python\na = 200\nb = 33\nc = 500\nif a \u003e b or a \u003e c:\n  print(\"At least one of the conditions is True\")\n\u003e\u003e \"At least one of the conditions is True\"\n```\n\n```python\na = 33\nb = 200\nif not a \u003e b:\n  print(\"a is NOT greater than b\")\n\u003e\u003e \"a is NOT greater than b\"\n```\n\n```python\nx = 41\n\nif x \u003e 10:\n  print(\"Above ten,\")\n  if x \u003e 20:\n    print(\"and also above 20!\")\n  else:\n    print(\"but not above 20.\")\n\u003e\u003e \"Above ten,\"\n   \"and also above 20!\"\n```\n\n\nWhile-Loops\n------\n![Monty Python](https://files.realpython.com/media/Python-while-Loops-Indefinite-Iteration_Watermarked.2dfa40d8e92c.jpg)\n```python\ni = 1\nwhile i \u003c 6:\n  print(i)\n  i += 1\n\u003e\u003e 1\n   2\n   3\n   4\n   5\n```\n\n```python\ni = 1\nwhile i \u003c 6:\n  print(i)\n  if i == 3:\n    break\n  i += 1\n\u003e\u003e 1\n   2\n   3\n```\n\n```python\ni = 0\nwhile i \u003c 6:\n  i += 1\n  if i == 3:\n    continue\n  print(i)\n\u003e\u003e 1\n   2\n   4\n   5\n   6\n```\n\n```python\ni = 1\nwhile i \u003c 6:\n  print(i)\n  i += 1\nelse:\n  print(\"i is no longer less than 6\")\n\u003e\u003e 1\n   2\n   3\n   4\n   5\n   \"i is no longer less than 6\"\n```\n\n\nfor-Loops\n-------\n![Monty Python](https://files.realpython.com/media/Python-for-Loops-Definite-Iteration_Watermarked.9c0d36b6de30.jpg)\n```python\nfruits = [\"apple\", \"banana\", \"cherry\"]\nfor x in fruits:\n  print(x)\n\u003e\u003e \"apple\"\n   \"banana\"\n   \"cherry\"\n```\n\n```python\nfor x in \"banana\":\n  print(x)\n\u003e\u003e 'b'\n   'a'\n   'n'\n   'a'\n   'n'\n   'a'\n```\n\n```python\nfruits = [\"apple\", \"banana\", \"cherry\"]\nfor x in fruits:\n  if x == \"banana\":\n    break\n  print(x)\n\u003e\u003e \"apple\"\n```\n\n```python\nfruits = [\"apple\", \"banana\", \"cherry\"]\nfor x in fruits:\n  if x == \"banana\":\n    continue\n  print(x)\n\u003e\u003e \"apple\"\n   \"cherry\"\n```\n\n```python\nfor x in range(6):\n  print(x)\n\u003e\u003e 0\n   1\n   2\n   3\n   4\n   5\n```\n\n```python\nfor x in range(2, 6):\n  print(x)\n\u003e\u003e 2\n   3\n   4\n   5\n```\n\n```python\nfor x in range(2, 30, 3):\n  print(x)\n\u003e\u003e 2\n   5\n   8\n   11\n   14\n   17\n   20\n   23\n   26\n   29\n```\n\n```python\nfor x in range(6):\n  print(x)\nelse:\n  print(\"Finally finished!\")\n\u003e\u003e 0\n   1\n   2\n   3\n   4\n   5\n   \"Finally finished!\"\n```\n\n```python\nfor x in range(6):\n  if x == 3: break\n  print(x)\nelse:\n  print(\"Finally finished!\")\n\u003e\u003e 0\n   1\n   2\n```\n\n```python\nadj = [\"red\", \"big\", \"tasty\"]\nfruits = [\"apple\", \"banana\", \"cherry\"]\n\nfor x in adj:\n  for y in fruits:\n    print(x, y)\n\u003e\u003e \"red apple\"\n   \"red banana\"\n   \"red cherry\"\n   \"big apple\"\n   \"big banana\"\n   \"big cherry\"\n   \"tasty apple\"\n   \"tasty banana\"\n   \"tasty cherry\"\n```\n\nFunctions\n-------------\n![Monty Python](https://files.realpython.com/media/Inner-Functions-What-Are-They-Good-For_Watermarked.995d44a06cdd.jpg)\n```python\ndef my_function():\n  print(\"Hello from a function\")\n\nmy_function()\n\u003e\u003e \"Hello from a function\"\n```\n\n```python\ndef myfunc():\n  x = 300\n  print(x)\nmyfunc()\n\u003e\u003e 300\n```\n\n```python\ndef myfunc():\n  x = 300\n  def myinnerfunc():\n    print(x)\n  myinnerfunc()\n\nmyfunc()\n\u003e\u003e 300\n```\n\n```python\nx = 300\ndef myfunc():\n  print(x)\n\nmyfunc()\nprint(x)\n\u003e\u003e 300\n\u003e\u003e 300\n```\n\n```python\nx = 300\ndef myfunc():\n  x = 200\n  print(x)\n\nmyfunc()\nprint(x)\n\u003e\u003e 200\n\u003e\u003e 300\n```\n\n```python\ndef myfunc():\n  global x\n  x = 300\n\nmyfunc()\nprint(x)\n\u003e\u003e 300\n```\n\n```python\nx = 300\ndef myfunc():\n  global x\n  x = 200\n\nmyfunc()\nprint(x)\n\u003e\u003e 200\n```\n\n```python\ndef my_function(fname):\n  print(fname + \" Refsnes\")\n\nmy_function(\"Emil\")\nmy_function(fname = \"Tobias\")\nmy_function(\"Linus\")\n\n\u003e\u003e \"Emil Refsnes\"\n\u003e\u003e \"Tobias Refsnes\"\n\u003e\u003e \"Linus Refsnes\"\n```\n\n```python\ndef my_function(fname, lname):\n  print(fname + \" \" + lname)\n\nmy_function(\"Emil\", \"Refsnes\")\n\u003e\u003e \"Emil Refsnes\"\n```\n\n```python\ndef my_function(*kids):  #  *  it's for more than one value\n  print(\"The youngest child is \" + kids[2])\n\nmy_function(\"Emil\", \"Tobias\", \"Linus\")\n\u003e\u003e \"The youngest child is Linus\"\n```\n\n```python\ndef my_function(child3, child2, child1):\n  print(\"The youngest child is \" + child3)\n\nmy_function(child1 = \"Emil\", child2 = \"Tobias\", child3 = \"Linus\")\n\u003e\u003e \"The youngest child is Linus\"\n```\n\n```python\ndef my_function(**kid):  # **  it's mean we don't need call number , just call that word\n  print(\"His last name is \" + kid[\"lname\"])\n\nmy_function(fname = \"Tobias\", lname = \"Refsnes\")\n\u003e\u003e \"His last name is Refsnes\"\n```\n\n```python\ndef my_function(country = \"Norway\"):\n  print(\"I am from \" + country)\n\nmy_function(\"Sweden\")\nmy_function(\"India\")\nmy_function()\nmy_function(\"Brazil\")\n\u003e\u003e \"I am from Sweden\"\n\u003e\u003e \"I am from India\"\n\u003e\u003e \"I am from Norway\"\n\u003e\u003e \"I am from Brazil\"\n```\n\n```python\ndef my_function(food):\n  for x in food:\n    print(x)\n\nfruits = [\"apple\", \"banana\", \"cherry\"]\nmy_function(fruits)\n\u003e\u003e \"apple\"\n   \"banana\"\n   \"cherry\"\n```\n\n```python\ndef my_function(x):\n  return 5 * x\n\nprint(my_function(3))\nprint(my_function(5))\nprint(my_function(9))\n\u003e\u003e 15\n\u003e\u003e 25\n\u003e\u003e 45\n```\n\n```python\ndef my_function(x, /):\n  print(x)\n\nmy_function(3)\n\u003e\u003e 3\n```\n\n```python\ndef my_function(*, x):\n  print(x)\n\nmy_function(x = 3)\n\u003e\u003e 3\n```\n\n```python\ndef my_function(a, b, /, *, c, d):\n  print(a + b + c + d)\n\nmy_function(5, 6, c = 7, d = 8)\n\u003e\u003e 26\n```\n\n```python\ndef tri_recursion(k):\n  if(k \u003e 0):\n    result = k + tri_recursion(k - 1)\n    print(result)\n  else:\n    result = 0\n  return result\n\nprint(\"\\n\\nRecursion Example Results\")\ntri_recursion(6)\n\n\u003e\u003e \"Recursion Example Results\"\n   1\n   3\n   6\n   10\n   15\n   21\n```\n\n```python\ndef shout(text): \n    return text.upper() \n \ndef whisper(text): \n    return text.lower() \n \ndef greet(func): \n    # storing the function in a variable \n    greeting = func(\"\"\"Hi, I am created by a function passed as an argument.\"\"\") \n    print (greeting) \n \ngreet(shout) \ngreet(whisper) \n\n\u003e\u003e \"HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.\"\n   \"hi, i am created by a function passed as an argument.\"\n```\n\n```python\ndef say_hello(name):\n    return f\"Hello {name}\"\n\ndef be_awesome(name):\n    return f\"Yo {name}, together we're the awesomest!\"\n\ndef greet_bob(greeter_func):\n    return greeter_func(\"Bob\")\n\ngreet_bob(say_hello)\n\u003e\u003e 'Hello Bob'\n\ngreet_bob(be_awesome)\n\u003e\u003e 'Yo Bob, together were the awesomest!'\n```\n\n```python\ndef parent():\n    print(\"Printing from parent()\")\n\n    def first_child():\n        print(\"Printing from first_child()\")\n\n    def second_child():\n        print(\"Printing from second_child()\")\n\n    second_child()\n    first_child()\n\nparent()\n\u003e\u003e \"Printing from parent()\"\n   \"Printing from second_child()\"\n   \"Printing from first_child()\n```\n\n### Decorator :\n\n**decorators are used in Python to modify the behavior of functions or classes. \nThey are higher-order functions that take a function or class as input and return a new function or class with modified behavior. \nDecorators are commonly used to add new functionality to existing code without changing the underlying implementation, \nmaking the code more usable and modular.**\n\n```python\n# for first , look at this and undrestand it :\n\ndef decorator(func):\n    def wrapper():\n        print(\"Something is happening before the function is called.\")\n        func()\n        print(\"Something is happening after the function is called.\")\n    return wrapper\n\ndef say_whee():\n    print(\"Whee!\")\n\nsay_whee = decorator(say_whee)\n\n\n\u003e\u003e \"Something is happening before the function is called.\"\n   \"Whee!\"\n   \"Something is happening after the function is called.\"\n\n\n# now we can do this with Decorator :\n\n\ndef decorator(func):\n    def wrapper():\n        print(\"Something is happening before the function is called.\")\n        func()\n        print(\"Something is happening after the function is called.\")\n    return wrapper\n\n@decorator\ndef say_whee():\n    print(\"Whee!\")\n\n\u003e\u003e \"Something is happening before the function is called.\"\n   \"Whee!\"\n   \"Something is happening after the function is called.\"\n```\n\n```python\ndef make_pretty(func):\n\n    def inner():\n        print(\"I got decorated\")\n        func()\n    return inner\n\n@make_pretty\ndef ordinary():\n    print(\"I am ordinary\")\n\nordinary()  \n\n\u003e\u003e \"I got decorated\"\n   \"I am ordinary\"\n```\n\n```python\ndef star(func):\n    def inner(*args, **kwargs):\n        print(\"*\" * 30)\n        func(*args, **kwargs)\n        print(\"*\" * 30)\n    return inner\n\ndef percent(func):\n    def inner(*args, **kwargs):\n        print(\"%\" * 30)\n        func(*args, **kwargs)\n        print(\"%\" * 30)\n    return inner\n\n@star\n@percent\ndef printer(msg):\n    print(msg)\nprinter(\"Hello\")\n\n\u003e\u003e '******************************\"\n   \"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\"\n   \"Hello\"\n   \"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\"\n   \"******************************\"\n```\n\n### generator :\n\n**Generator in Python is an easy way to generate browsers and with this feature you can easily control one and exit it at any time. \nIn the case of ordinary functions in Python, the issue of speed and amount of memory is raised. \nYou have problems in terms of speed and memory in a Python function, \nwhich have been solved to a large extent by using Generator in Python.**\n\n```python\ndef simpleGeneratorFun(): \n    yield 1            \n    yield 2            \n    yield 3            \n   \nfor value in simpleGeneratorFun():  \n    print(value)\n\n\u003e\u003e 1\n   2\n   3\n\n\n# Or we can do this :\n\n\ndef simpleGeneratorFun(): \n    yield 1\n    yield 2\n    yield 3\n   \nx = simpleGeneratorFun() \nprint(next(x)) \nprint(next(x)) \nprint(next(x))\n\n\u003e\u003e 1\n   2\n   3\n```\n\n```python\ndef fib(limit): \n      \n    a, b = 0, 1\n    while a \u003c limit: \n        yield a \n        a, b = b, a + b \n  \nx = fib(5) \n\nprint(next(x))  \nprint(next(x)) \nprint(next(x)) \nprint(next(x)) \nprint(next(x)) \n\nprint(\"\\nUsing for in loop\") \nfor i in fib(5):  \n    print(i)\n\n\n\u003e\u003e 0\n   1\n   1\n   2\n   3\n   \"Using for in loop\"\n   0\n   1\n   1\n   2\n   3\n```\n\n### Name \u0026 Main :\n\n**Management and control function**\n\n```python\nfrom time import sleep\n\nprint(\"This is my file to demonstrate best practices.\")\n\ndef process_data(data):\n    print(\"Beginning data processing...\")\n    modified_data = data + \" that has been modified\"\n    sleep(3)\n    print(\"Data processing finished.\")\n    return modified_data\n\ndef main():\n    data = \"My data read from the Web\"\n    print(data)\n    modified_data = process_data(data)\n    print(modified_data)\n\nif __name__ == \"__main__\":\n    main()\n\n\n\u003e\u003e \"This is my file to demonstrate best practices.\"\n   \"My data read from the Web\"\n   \"Beginning data processing...\"\n   \"Data processing finished.\"\n   \"My data read from the Web that has been modified\"\n\n\"\"\"  With this method, it is possible to manage which function is executed and in what model the scripts are executed  \"\"\"\n\n```\n\n```python\ndef echo(text: str, repetitions: int = 3) -\u003e str:\n    \"\"\"Imitate a real-world echo.\"\"\"\n    echoed_text = \"\"\n    for i in range(repetitions, 0, -1):\n        echoed_text += f\"{text[-i:]}\\n\"\n    return f\"{echoed_text.lower()}.\"\n\nif __name__ == \"__main__\":\n    text = input(\"Yell something at a mountain: \")\n    print(echo(text))\n\n\n\u003e\u003e Yell something at a mountain: hh\n   hh\n   hh\n   h \n   . \n```\n\nlambda\n--------\n![Monty Python](https://files.realpython.com/media/How-to-Use-Python-Lambda-Functions_Watermarked.2afa4f5ea5d4.jpg)\n**lambda is a keyword in Python for defining the anonymous function. argument(s) is a placeholder, that is a variable that will be used to hold the value you want to pass into the function expression. A lambda function can have multiple variables depending on what you want to achieve.**\n```python\nx = lambda a : a + 10\nprint(x(5))\n\u003e\u003e 15\n```\n\n```python\nx = lambda a, b : a * b\nprint(x(5, 6))\n\u003e\u003e 30\n```\n\n```python\nx = lambda a, b, c : a + b + c\nprint(x(5, 6, 2))\n\u003e\u003e 13\n```\n\n```python\ndef myfunc(n):\n  return lambda a : a * n\n\nmydoubler = myfunc(2)\nprint(mydoubler(11))\n\u003e\u003e 22\n```\n\n```python\ndef myfunc(n):\n  return lambda a : a * n\n\nmytripler = myfunc(3)\nprint(mytripler(11))\n\u003e\u003e 22\n```\n\n```python\ndef myfunc(n):\n  return lambda a : a * n\n\nmydoubler = myfunc(2)\nmytripler = myfunc(3)\nprint(mydoubler(11))\nprint(mytripler(11))\n\u003e\u003e 22\n\u003e\u003e 33\n```\n\n\niterators\n---------\n![Monty Python](https://files.realpython.com/media/Iterators-and-Iterables-in-Python-What-Are-They-and-How-to-Use-Them_Watermarked.5df74332ac58.jpg)\n```python\nmytuple = (\"apple\", \"banana\", \"cherry\")\nmyit = iter(mytuple)\n\nprint(next(myit))\nprint(next(myit))\nprint(next(myit))\n\u003e\u003e \"apple\"\n\u003e\u003e \"banana\"\n\u003e\u003e \"cherry\"\n```\n\n```python\nmystr = \"banana\"\nmyit = iter(mystr)\n\nprint(next(myit))\nprint(next(myit))\nprint(next(myit))\nprint(next(myit))\nprint(next(myit))\nprint(next(myit))\n\u003e\u003e 'b'\n\u003e\u003e 'a'\n\u003e\u003e 'n'\n\u003e\u003e 'a'\n\u003e\u003e 'n'\n\u003e\u003e 'a'\n```\n\n```python\nmytuple = (\"apple\", \"banana\", \"cherry\")\nfor x in mytuple:\n  print(x)\n\u003e\u003e \"apple\"\n   \"banana\"\n   \"cherry\"\n```\n\n\nmake-my-library\n------\n**for first make a python file as app.py**\n**and write some func or class :**\n```python\ndef greeting(name):\n  print(\"Hello, \" + name)\n```\n**and open a nother python file as try.py and wrire this :**\n```python\nimport app\n\napp.greeting(\"Jonathan\")\n\u003e\u003e \"Hello, Jonathan\"\n```\n**now you have your own library**\n\n### example :\n**app.py :**\n```python\nperson1 = {\n  \"name\": \"John\",\n  \"age\": 36,\n  \"country\": \"Norway\"\n}\n```\n**try.py :**\n```python\nimport app\na = app.person1[\"age\"]\nprint(a)\n\u003e\u003e 36\n\n# or\n\nimport app as mx\na = mx.person1[\"age\"]\nprint(a)\n```\n\nDatetime\n------\n![Monty Python](https://files.realpython.com/media/How-to-Use-Python-datetime-With-Examples_Watermarked.2676ca0aacf2.jpg)\n```python\nimport datetime\nx = datetime.datetime.now()\nprint(x)\n\u003e\u003e 2024-02-21 05:37:25.261486\n```\n\n```python\nimport datetime\nx = datetime.datetime.now()\nprint(x.year)\nprint(x.strftime(\"%A\"))\n\u003e\u003e 2024\n\u003e\u003e Wednesday\n```\n\n```python\nimport datetime\nx = datetime.datetime(2020, 5, 17)\nprint(x)\n\u003e\u003e 2020-05-17 00:00:00\n```\n\n```python\nimport datetime\nx = datetime.datetime(2018, 6, 1)\nprint(x.strftime(\"%B\"))\n\u003e\u003e June\n```\n\n**`%a`\tWeekday, short version\tWed.**\n\n**`%A`\tWeekday, full version\tWednesday.**\n\n**`%w`\tWeekday as a number 0-6, 0 is Sunday\t3.**\n\n**`%d`\tDay of month 01-31\t31.**\n\n**`%b`\tMonth name, short version\tDec.**\n\n**`%B`\tMonth name, full version\tDecember.**\n\n**`%m`\tMonth as a number 01-12\t12.**\n\n**`%y`\tYear, short version, without century\t18.**\n\n**`%Y`\tYear, full version\t2018.**\n\n**`%H`\tHour 00-23\t17.**\n\n**`%I`\tHour 00-12\t05.**\n\n**`%p`\tAM/PM\tPM.**\n\n**`%M`\tMinute 00-59\t41.**\n\n**`%S`\tSecond 00-59\t08.**\n\n**`%f`\tMicrosecond 000000-999999\t548513.**\n\n**`%z`\tUTC offset\t+0100.**\n\n**`%Z`\tTimezone\tCST.**\n\n**`%j`\tDay number of year 001-366\t365.**\n\n**`%U`\tWeek number of year, Sunday as the first day of week, 00-53\t52.**\n\n**`%W`\tWeek number of year, Monday as the first day of week, 00-53\t52.**\n\n**`%c`\tLocal version of date and time\tMon Dec 31 17:41:00 2018.**\n\n**`%C`\tCentury\t20.**\n\n**`%x`\tLocal version of date\t12/31/18.**\n\n**`%X`\tLocal version of time\t17:41:00.**\n\n**`%%`\tA % character\t%.**\n\n**`%G`\tISO 8601 year\t2018.**\n\n**`%u`\tISO 8601 weekday (1-7)\t1.**\n\n**`%V`\tISO 8601 weeknumber (01-53)\t01.**\n\n\nMath\n------\n![Monty Python](https://files.realpython.com/media/Pythons-Math-Module-Guide_Watermarked.c882e267cbd0.jpg)\n```python\nx = min(5, 10, 25)\ny = max(5, 10, 25)\nprint(x)\nprint(y)\n\u003e\u003e 5\n\u003e\u003e 25\n```\n\n```python\nx = abs(-7.25)\nprint(x)\n\u003e\u003e 7.25\n```\n\n```python\nx = pow(4, 3)\nprint(x)\n\u003e\u003e 64\n```\n\n```python\nimport math\nx = math.sqrt(64)\nprint(x)\n\u003e\u003e 8.0\n```\n\n```python\nimport math\nx = math.ceil(1.4)\ny = math.floor(1.4)\nprint(x) # returns 2\nprint(y) # returns 1\n\u003e\u003e 2\n\u003e\u003e 1\n```\n\n```python\nimport math\nx = math.pi\nprint(x)\n\u003e\u003e 3.141592653589793\n```\n\n### All math methods :\n**.math.ceil() (Rounds a number up to the nearest integer)**\n```python\nimport math\nprint(math.ceil(1.4))\nprint(math.ceil(5.3))\nprint(math.ceil(-5.3))\nprint(math.ceil(22.6))\nprint(math.ceil(10.0))\n\u003e\u003e 2\n\u003e\u003e 6\n\u003e\u003e -5\n\u003e\u003e 23\n\u003e\u003e 10\n```\n\n**.math.comb() (Returns the number of ways to choose k items from n items without repetition and order)**\n```python\nimport math\nn = 7\nk = 5\nprint (math.comb(n, k))\n\u003e\u003e 21\n```\n\n**.math.copysign() (Returns a float consisting of the value of the first parameter and the sign of the second parameter)**\n```python\nimport math  \nprint(math.copysign(4, -1))\nprint(math.copysign(-8, 97.21))\nprint(math.copysign(-43, -76))\n\u003e\u003e -4.0\n\u003e\u003e 8.0\n\u003e\u003e -43.0\n```\n\n**.math.cos() (Returns the cosine of a number)**\n```python\nimport math\nprint (math.cos(0.00))\nprint (math.cos(-1.23))\nprint (math.cos(10))\nprint (math.cos(3.14159265359))\n\u003e\u003e 1.0\n\u003e\u003e 0.3342377271245026\n\u003e\u003e -0.8390715290764524\n\u003e\u003e -1.0\n```\n\n**.math.degrees() (Converts an angle from radians to degrees)**\n```python\nimport math\nprint (math.degrees(8.90))\nprint (math.degrees(-20))\nprint (math.degrees(1))\nprint (math.degrees(90))\n\u003e\u003e 509.9324376664327\n\u003e\u003e -1145.9155902616465\n\u003e\u003e 57.29577951308232\n\u003e\u003e 5156.620156177409\n```\n\n**.math.dist() (Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point)**\n```python\nimport math\n\np = [3]\nq = [1]\nprint (math.dist(p, q))\n\u003e\u003e 2.0\n\np = [3, 3]\nq = [6, 12]\nprint (math.dist(p, q))\n\u003e\u003e 9.486832980505138\n```\n\n**.math.fabs() (Returns the absolute value of a number)**\n```python\nimport math\nprint(math.fabs(-66.43))\nprint(math.fabs(-7))\n\u003e\u003e 66.43\n\u003e\u003e 7.0\n```\n\n**.math.floor() (Rounds a number down to the nearest integer)**\n```python\nimport math\nprint(math.floor(0.6))\nprint(math.floor(1.4))\nprint(math.floor(5.3))\nprint(math.floor(-5.3))\nprint(math.floor(22.6))\nprint(math.floor(10.0))\n\u003e\u003e 0\n\u003e\u003e 1\n\u003e\u003e 5\n\u003e\u003e -6\n\u003e\u003e 22\n\u003e\u003e 10\n```\n\n**.math.fmod() (Returns the remainder of x/y)**\n```python\nimport math\nprint(math.fmod(20, 4))\nprint(math.fmod(20, 3))\nprint(math.fmod(15, 6))\nprint(math.fmod(-10, 3))\nprint(math.fmod(0, 0))\n\u003e\u003e 0.0\n\u003e\u003e 2.0\n\u003e\u003e 3.0\n\u003e\u003e -1.0\n```\n\n**.math.fsum() (Returns the sum of all items in any iterable (tuples, arrays, lists, etc.))**\n```python\nimport math\nprint(math.fsum([1, 2, 3, 4, 5]))\nprint(math.fsum([100, 400, 340, 500]))\nprint(math.fsum([1.7, 0.3, 1.5, 4.5]))\n\u003e\u003e 15.0\n\u003e\u003e 1340.0\n\u003e\u003e 8.0\n```\n\n**.math.gcd() (Returns the greatest common divisor of two integers)**\n```python\nimport math\nprint (math.gcd(3, 6))\nprint (math.gcd(6, 12))\nprint (math.gcd(12, 36))\nprint (math.gcd(-12, -36))\nprint (math.gcd(5, 12))\nprint (math.gcd(10, 0))\nprint (math.gcd(0, 34))\nprint (math.gcd(0, 0))\n\u003e\u003e 3\n\u003e\u003e 6\n\u003e\u003e 12\n\u003e\u003e 12\n\u003e\u003e 1\n\u003e\u003e 10\n\u003e\u003e 34\n\u003e\u003e 0\n```\n\n**.math.isclose() (Checks whether two values are close to each other, or not)**\n```python\nimport math\nprint(math.isclose(1.233, 1.4566))\nprint(math.isclose(1.233, 1.233))\nprint(math.isclose(1.233, 1.24))\nprint(math.isclose(1.233, 1.233000001))\n\u003e\u003e False\n\u003e\u003e True\n\u003e\u003e False\n\u003e\u003e True\n```\n\n\nJSON\n------\n![Monty Python](https://files.realpython.com/media/Working-With-JSON-Data-in-Python_Watermarked.66a8fdcb8859.jpg)\n**JSON is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays. It is a commonly used data format with diverse uses in electronic data interchange, including that of web applications with servers.**\n\n**In Python, why should one use JSON scheme instead of a dictionary?It is apples vs. oranges comparison: JSON is a data format (a string), Python dictionary is a data structure (in-memory object).\nIf you need to exchange data between different (perhaps even non-Python) processes then you could use JSON format to serialize your Python dictionary.**\n```python\nimport json\n# some JSON:\nx =  '{ \"name\":\"John\", \"age\":30, \"city\":\"New York\"}'\n# parse x:\ny = json.loads(x)\n# the result is a Python dictionary:\nprint(y[\"age\"])\n\u003e\u003e 30\n```\n\n```python\nimport json\n# a Python object (dict):\nx = {\n  \"name\": \"John\",\n  \"age\": 30,\n  \"city\": \"New York\"\n}\n# convert into JSON:\ny = json.dumps(x)\n# the result is a JSON string:\nprint(y)\n\u003e\u003e {\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}\n```\n\n```python\nimport json\nprint(json.dumps({\"name\": \"John\", \"age\": 30}))\nprint(json.dumps([\"apple\", \"bananas\"]))\nprint(json.dumps((\"apple\", \"bananas\")))\nprint(json.dumps(\"hello\"))\nprint(json.dumps(42))\nprint(json.dumps(31.76))\nprint(json.dumps(True))\nprint(json.dumps(False))\nprint(json.dumps(None))\n\u003e\u003e {\"name\": \"John\", \"age\": 30}\n\u003e\u003e [\"apple\", \"bananas\"]\n\u003e\u003e [\"apple\", \"bananas\"]\n\u003e\u003e \"hello\"\n\u003e\u003e 42\n\u003e\u003e 31.76\n\u003e\u003e True\n\u003e\u003e False\n\u003e\u003e Null\n```\n\n```python\nimport json\nx = {\n  \"name\": \"John\",\n  \"age\": 30,\n  \"married\": True,\n  \"divorced\": False,\n  \"children\": (\"Ann\",\"Billy\"),\n  \"pets\": None,\n  \"cars\": [\n    {\"model\": \"BMW 230\", \"mpg\": 27.5},\n    {\"model\": \"Ford Edge\", \"mpg\": 24.1}\n  ]\n}\nprint(json.dumps(x))\n\u003e\u003e {\"name\": \"John\", \"age\": 30, \"married\": true, \"divorced\": false, \"children\": [\"Ann\", \"Billy\"], \"pets\": null, \"cars\": [{\"model\": \"BMW 230\", \"mpg\": 27.5}, {\"model\": \"Ford Edge\", \"mpg\": 24.1}]}\n```\n\n\nRegEx\n------\n![Monty Python](https://files.realpython.com/media/Regular-Expressions-Regexes-in-Python-Part-1_Watermarked.0423050c5371.jpg)\n```python\nimport re\ntxt = \"The rain in Spain\"\nx = re.findall(\"ai\", txt)\nprint(x)\n\u003e\u003e ['ai', 'ai']\n```\n\n**`findall`\tReturns a list containing all matches.**\n\n**`search`\tReturns a Match object if there is a match anywhere in the string.**\n\n**`split`\tReturns a list where the string has been split at each match.**\n\n**`sub`\tReplaces one or many matches with a string.**\n\n**`[]`\tA set of characters.**\n\n**`\\`\tSignals a special sequence (can also be used to escape special characters).**\n\n**`.`\tAny character (except newline character).**\n\n**`^`\tStarts with.**\n\n**`$`\tEnds with.**\n\n**`*`\tZero or more occurrences.**\n\n**`+`\tOne or more occurrences.**\n\n**`?`\tZero or one occurrences.**\n\n**`{}`\tExactly the specified number of occurrences.**\n\n**`|`\tEither or.**\n\n**`()`\tCapture and group.**\n\n**Regex online : https://regex101.com/**\n\n\nTry-Except\n------\n![Monty Python](https://files.realpython.com/media/Python_Exceptions_Watermark.47f814fbeced.jpg)\n* **`try`\tblock lets you test a block of code for errors.**\n* **`except`\tblock lets you handle the error.**\n* **`else`\tblock lets you execute code when there is no error.**\n* **`finally`\tblock lets you execute code, regardless of the result of the try- and except blocks.**\n\n```python\ndef divide(x, y):\n    try:\n        # Floor Division : Gives only Fractional Part as Answer\n        result = x // y\n        print(\"Yeah ! Your answer is :\", result)\n    except ZeroDivisionError:\n        print(\"Sorry ! You are dividing by zero \")\n \n\ndivide(1, 1)\n\u003e\u003e \"Yeah ! Your answer is : 1\"\n\ndivide(1, 0)\n\u003e\u003e \"Sorry ! You are dividing by zero\"\n```\n\n```python\ndef AbyB(a , b):\n    try:\n        c = ((a+b) // (a-b))\n    except ZeroDivisionError:\n        print (\"a/b result in 0\")\n    else:\n        print (c)\n\n\nAbyB(2.0, 3.0)\n\u003e\u003e -5.0\nAbyB(3.0, 3.0)\n\u003e\u003e \"a/b result in 0\"\n```\n\n```python\ntry: \n    k = 5//0 # raises divide by zero exception. \n    print(k) \n    \nexcept ZeroDivisionError:   # handles zerodivision exception     \n    print(\"Can't divide by zero\") \n        \nfinally: \n    # this block is always executed  \n    # regardless of exception generation. \n    print('This is always executed')  \n\n\n\u003e\u003e \"Can't divide by zero\"\n\u003e\u003e \"This is always executed\" \n```\n\n\nInput\n------\n![Monty Python](https://files.realpython.com/media/Basic-Input-Output-and-String-Formatting-in-Python_Watermarked.65ba5b535841.jpg)\n```python\nusername = input(\"Enter username:\")\nprint(\"Username is: \" + username)\n\u003e\u003e \"Username is: iran\"\n```\n\n```python\nnum1 = int(input())\nnum2 = int(input())\nprint(num1 + num2)\n```\n\n```python\nnum1 = float(input())\nnum2 = float(input())\nprint(num1 + num2)\n```\n\n```python\n# taking two inputs at a time\nx, y = input(\"Enter two values: \").split()\nprint(\"Number of boys: \", x)\nprint(\"Number of girls: \", y)\n```\n\n\nString Formatting\n------\n```python\nprice = 49\ntxt = \"The price is {} dollars\"\nprint(txt.format(price))\n\u003e\u003e \"The price is 49 dollars\"\n```\n\n```python\nquantity = 3\nitemno = 567\nprice = 49\nmyorder = \"I want {} pieces of item number {} for {:.2f} dollars.\"\nprint(myorder.format(quantity, itemno, price))\n\u003e\u003e \"I want 3 pieces of item number 567 for 49.00 dollars.\"\n```\n\n\nFile-Handling\n------\n![Monty Python](https://files.realpython.com/media/Reading-and-Writing-Files-in-Python_Watermarked.0d394921fd90.jpg)\n**`close()`\tCloses the file.**\n\n**`detach()`\tReturns the separated raw stream from the buffer.**\n\n**`fileno()`\tReturns a number that represents the stream, from the operating system's perspective.**\n\n**`flush()`\tFlushes the internal buffer.**\n\n**`isatty()`\tReturns whether the file stream is interactive or not.**\n\n**`read()`\tReturns the file content.**\n\n**`readable()`\tReturns whether the file stream can be read or not.**\n\n**`readline()`\tReturns one line from the file.**\n\n**`readlines()`\tReturns a list of lines from the file.**\n\n**`seek()`\tChange the file position.**\n\n**`seekable()`\tReturns whether the file allows us to change the file position.**\n\n**`tell()`\tReturns the current file position.**\n\n**`truncate()`\tResizes the file to a specified size.**\n\n**`writable()`\tReturns whether the file can be written to or not.**\n\n**`write()`\tWrites the specified string to the file.**\n\n**`writelines()`\tWrites a list of strings to the file.**\n\n* **`\"r\"`\tRead - Default value. Opens a file for reading, error if the file does not exist.**\n* **`\"a\"`\tAppend - Opens a file for appending, creates the file if it does not exist.**\n* **`\"w\"`\tWrite - Opens a file for writing, creates the file if it does not exist.**\n* **`\"x\"`\tCreate - Creates the specified file, returns an error if the file exists.**\n* **`\"t\"`\tText - Default value. Text mode.**\n* **`\"b\"`\tBinary - Binary mode (e.g. images).**\n  \n```python\nf = open(\"demofile.txt\")\n```\n\n```python\nf = open(\"demofile.txt\", \"rt\")\n```\n\n```python\nf = open(\"demofile.txt\", \"r\")\nprint(f.read())\n```\n\n```python\nf = open(\"D:\\\\myfiles\\welcome.txt\", \"r\")\nprint(f.read())\n```\n\n```python\nf = open(\"demofile.txt\", \"r\")\nprint(f.read(5))  # Return the 5 first characters of the file\n```\n\n```python\nf = open(\"demofile.txt\", \"r\")\nprint(f.readline())\n```\n\n```python\nf = open(\"demofile.txt\", \"r\")\nprint(f.readline())\nf.close()\n```\n\n### Write to an Existing File :\n**`\"a\"`\tAppend - will append to the end of the file.**\n\n**`\"w\"`\tWrite - will overwrite any existing content.**\n```python\nf = open(\"demofile2.txt\", \"a\")\nf.write(\"Now the file has more content!\")\nf.close()\n#open and read the file after the appending:\nf = open(\"demofile2.txt\", \"r\")\nprint(f.read())\n\u003e\u003e \"Now the file has more content!\"\n\n\nf = open(\"demofile3.txt\", \"w\")\nf.write(\"Woops! I have deleted the content!\")\nf.close()\n#open and read the file after the overwriting:\nf = open(\"demofile3.txt\", \"r\")\nprint(f.read())\n\u003e\u003e \"Woops! I have deleted the content!\"\n```\n\n### Create a New File :\n**`\"x\"`\tCreate - will create a file, returns an error if the file exist.**\n\n**`\"a\"`\tAppend - will create a file if the specified file does not exist.**\n\n**`\"w\"`\tWrite - will create a file if the specified file does not exist.**\n```python\nf = open(\"myfile.txt\", \"x\")\n\nf = open(\"myfile.txt\", \"w\")\n```\n\n### Delete a File :\n```python\nimport os\nos.remove(\"demofile.txt\")\n```\n\n### Check if File exist :\n```python\nimport os\nif os.path.exists(\"demofile.txt\"):\n  os.remove(\"demofile.txt\")\nelse:\n  print(\"The file does not exist\")\n```\n\n### Delete Folder :\n```python\nimport os\nos.rmdir(\"myfolder\")\n```\n\n### Reading an Entire File :\n```python\nwith open('New Text Document.txt') as file_object:\n contents = file_object.read()\n print(contents) \n```\n\n### File Paths :\n```python\nfile_path = 'C:/Users/NAJAFI/Desktop/New Text Document.txt'\nwith open(file_path) as file_object:\n    print(file_object)\n\n\u003e\u003e \u003c_io.TextIOWrapper name='C:/Users/NAJAFI/Desktop/New Text Document.txt' mode='r' encoding='cp1252'\u003e\n```\n\n### Reading Line by Line :\n```python\nfile_path = 'C:/Users/NAJAFI/Desktop/New Text Document.txt'\nwith open(file_path) as file_object:\n for line in file_object:\n  print(line)\n    \n\u003e\u003e \"hello world\"\n```\n\n### Writing to an Empty File :\n```python\nfile_path = 'C:/Users/NAJAFI/Desktop/New Text Document.txt'\n\nwith open(file_path, 'w') as file_object:\n file_object.write(\"I love programming.\") # for first it clean the file and write\n\nwith open(file_path) as file_object:\n for line in file_object:\n  print(line)\n    \n\u003e\u003e \"I love programming.\"\n```\n\n### Appending to a File :\n```python\nfile_path = 'C:/Users/NAJAFI/Desktop/New Text Document.txt'\n\nwith open(file_path, 'a') as file_object:\n file_object.write(\"\\n\")\n file_object.write(\"I also love finding meaning in large datasets.\\n\")\n file_object.write(\"I love creating apps that can run in a browser.\\n\")\n\nwith open(file_path) as file_object:\n for line in file_object:\n  print(line)\n    \n\u003e\u003e \"I love programming.\"\n   \n   \"I also love finding meaning in large datasets.\"\n\n   \"I love creating apps that can run in a browser.\"\n```\n\n\nBuilt-In-Functions\n------\n### abs() (Returns the absolute value of a number) :\n```python\nx = abs(-7.25)\nprint(x)\n\u003e\u003e 7.25\n```\n\n### all() (Returns True if all items in an iterable object are true) :\n```python\nmylist = [True, True, True]\nx = all(mylist)\nprint(x)\n\u003e\u003e True\n```\n\n### any() (Returns True if any item in an iterable object is true) :\n```python\nmylist = [False, True, False]\nx = any(mylist)\nprint(x)\n\u003e\u003e True\n```\n\n### ascii() (Returns a readable version of an object. Replaces none-ascii characters with escape character) :\n```python\nx = ascii(\"My name is Ståle\")\nprint(x)\n\u003e\u003e 'My name is St\\xe5le'\n```\n\n### bin() (Returns the binary version of a number) :\n```python\nx = bin(36)\nprint(x)\n\u003e\u003e 0b100100\n```\n\n### bool() (Returns the boolean value of the specified object) :\n```python\nx = bool(1)\nprint(x)\n\u003e\u003e True\n```\n\n### bytearray() (Returns an array of bytes) :\n```python\nx = bytearray(4)\nprint(x)\n\u003e\u003e bytearray(b'\\x00\\x00\\x00\\x00')\n```\n\n### bytes() (Returns a bytes object) :\n```python\nx = bytes(4)\nprint(x)\n\u003e\u003e b'\\x00\\x00\\x00\\x00'\n```\n\n### callable() (Returns True if the specified object is callable, otherwise False) :\n```python\nx = 5\nprint(callable(x))\n\u003e\u003e False\n```\n\n### chr() (Returns a character from the specified Unicode code.) :\n```python\nx = chr(97)\nprint(x)\n\u003e\u003e 'a'\n```\n\n### complex() (Returns a complex number) :\n```python\nx = complex(3, 5)\nprint(x)\n\u003e\u003e (3+5j)\n```\n\n### dir() (Returns a list of the specified object's properties and methods) :\n```python\nclass Person:\n  name = \"John\"\n  age = 36\n  country = \"Norway\"\n\nprint(dir(Person))\n\u003e\u003e ['__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__', 'age', 'country', 'name']\n```\n\n### divmod() (Returns the quotient and the remainder when argument1 is divided by argument2) :\n```python\nx = divmod(5, 2)\nprint(x)\n\u003e\u003e (2, 1)\n```\n\n### enumerate() (Takes a collection (e.g. a tuple) and returns it as an enumerate object) :\n```python\nx = ('apple', 'banana', 'cherry')\ny = enumerate(x)\nprint(y)\n\u003e\u003e \u003cenumerate object at 0x14f74341f400\u003e\n```\n\n### eval() (Evaluates and executes an expression) :\n```python\nx = 'print(55)'\neval(x)\nprint(x)\n\u003e\u003e 55\n```\n\n### exec() (Executes the specified code (or object)) :\n```python\nx = 'name = \"John\"\\nprint(name)'\nexec(x)\n\u003e\u003e \"John\"\n```\n\n### filter() (Use a filter function to exclude items in an iterable object) :\n```python\nages = [5, 12, 17, 18, 24, 32]\n\ndef myFunc(x):\n  if x \u003c 18:\n    return False\n  else:\n    return True\n\nadults = filter(myFunc, ages)\n\nfor x in adults:\n  print(x)\n\u003e\u003e 18\n   24\n   32\n```\n\n### float() (Returns a floating point number) :\n```python\nx = float(3)\nprint(x)\n\u003e\u003e 3.0\n```\n\n### format() (Formats a specified value) :\n**`'\u003c'` Left aligns the result (within the available space)**\n\n**`'\u003e'` Right aligns the result (within the available space)**\n\n**`'^'` Center aligns the result (within the available space)**\n\n**`'='` Places the sign to the left most position**\n\n**`'+'` Use a plus sign to indicate if the result is positive or negative**\n\n**`'-'` Use a minus sign for negative values only**\n\n**`' '` Use a leading space for positive numbers**\n\n**`','` Use a comma as a thousand separator**\n\n**`'_'` Use a underscore as a thousand separator**\n\n**`'b'` Binary format**\n\n**`'c'` Converts the value into the corresponding unicode character**\n\n**`'d'` Decimal format**\n\n**`'e'` Scientific format, with a lower case e**\n\n**`'E'` Scientific format, with an upper case E**\n\n**`'f'` Fix point number format**\n\n**`'F'` Fix point number format, upper case**\n\n**`'g'` General format**\n\n**`'G'` General format (using a upper case E for scientific notations)**\n\n**`'o'` Octal format**\n\n**`'x'` Hex format, lower case**\n\n**`'X'` Hex format, upper case**\n\n**`'n'` Number format**\n\n**`'%'` Percentage format**\n```python\nx = format(0.5, '%')\nprint(x)\n\u003e\u003e 50.000000%\n```\n\n### frozenset() (Returns a frozenset object) :\n```python\nmylist = ['apple', 'banana', 'cherry']\nx = frozenset(mylist)\nprint(x)\n\u003e\u003e frozenset({'banana', 'cherry', 'apple'})\n```\n\n### hex() (Converts a number into a hexadecimal value) :\n```python\nx = hex(255)\nprint(x)\n\u003e\u003e 0xff\n```\n\n### id() (Returns the id of an object) :\n```python\nx = ('apple', 'banana', 'cherry')\ny = id(x)\nprint(y)\n\u003e\u003e 23082267064192\n```\n\n### isinstance() (Returns True if a specified object is an instance of a specified object) :\n```python\nx = isinstance(5, int)\nprint(x)\n\u003e\u003e True\n```\n\n### iter() (Returns an iterator object) :\n```python\nx = iter([\"apple\", \"banana\", \"cherry\"])\nprint(next(x))\nprint(next(x))\nprint(next(x))\n\u003e\u003e \"apple\"\n\u003e\u003e \"banana\"\n\u003e\u003e \"cherry\"\n```\n\n### map() (Returns the specified iterator with the specified function applied to each item) :\n```python\ndef myfunc(n):\n  return len(n)\nx = map(myfunc, ('apple', 'banana', 'cherry'))\nprint(x)\n\u003e\u003e \u003cmap object at 0x1481154c4130\u003e\n```\n\n```python\ndef square(number):\n    return number ** 2\n\n\nnumbers = [1, 2, 3, 4, 5]\nsquared = map(square, numbers)\n\nlist(squared)\n\u003e\u003e [1, 4, 9, 16, 25]\n```\n\n```python\nstr_nums = [\"4\", \"8\", \"6\", \"5\", \"3\", \"2\", \"8\", \"9\", \"2\", \"5\"]\n\nint_nums = map(int, str_nums)\nprint(int_nums)\n\u003e\u003e \u003cmap object at 0x7fb2c7e34c70\u003e\n\nprint(list(int_nums))\n\u003e\u003e [4, 8, 6, 5, 3, 2, 8, 9, 2, 5]\n\nprint(str_nums)\n\u003e\u003e [\"4\", \"8\", \"6\", \"5\", \"3\", \"2\", \"8\", \"9\", \"2\", \"5\"]\n```\n\n```python\nfirst_it = [1, 2, 3]\nsecond_it = [4, 5, 6, 7]\n\nprint(list(map(pow, first_it, second_it)))\n\u003e\u003e [1, 32, 729]\n```\n\n```python\nstring_it = [\"processing\", \"strings\", \"with\", \"map\"]\nlist(map(str.capitalize, string_it))\n\u003e\u003e ['Processing', 'Strings', 'With', 'Map']\n\nlist(map(str.upper, string_it))\n\u003e\u003e ['PROCESSING', 'STRINGS', 'WITH', 'MAP']\n\nlist(map(str.lower, string_it))\n\u003e\u003e ['processing', 'strings', 'with', 'map']\n```\n\n```python\nimport math\n\nnumbers = [1, 2, 3, 4, 5, 6, 7]\n\nprint(list(map(math.factorial, numbers)))\n\u003e\u003e [1, 2, 6, 24, 120, 720, 5040]\n```\n\n### max() (Returns the largest item in an iterable) :\n```python\nx = max(5, 10)\nprint(x)\n\u003e\u003e 10\n```\n\n### memoryview() (Returns a memory view object) :\n```python\nx = memoryview(b\"Hello\")\n\nprint(x)\n\u003e\u003e \u003cmemory at 0x1495289cfa00\u003e\n\n#return the Unicode of the first character\nprint(x[0])\n\u003e\u003e 72\n\n#return the Unicode of the second character\nprint(x[1])\n\u003e\u003e 101\n```\n\n### min() (Returns the smallest item in an iterable) :\n```python\nx = min(5, 10)\nprint(x)\n\u003e\u003e 5\n```\n\n### next() (Returns the next item in an iterable) :\n```python\nmylist = iter([\"apple\", \"banana\", \"cherry\"])\nx = next(mylist)\nprint(x)\n\u003e\u003e \"apple\"\nx = next(mylist)\nprint(x)\n\u003e\u003e \"banana\"\nx = next(mylist)\nprint(x)\n\u003e\u003e \"cherry\"\n```\n\n### object() (Returns a new object) :\n```python\nx = object()\nprint(x)\n\u003e\u003e \u003cobject object at 0x15447e7c4d70\u003e\n```\n\n### oct() (Converts a number into an octal) :\n```python\nx = oct(12)\nprint(x)\n\u003e\u003e 0o14\n```\n\n### ord() (Convert an integer representing the Unicode of the specified character) :\n```python\nx = ord(\"h\")\nprint(x)\n\u003e\u003e 104\n```\n\n### range() (Returns a sequence of numbers, starting from 0 and increments by 1 (by default)) :\n```python\nx = range(6)\nfor n in x:\n  print(n)\n\u003e\u003e 0\n   1\n   2\n   3\n   4\n   5\n\n\nx = range(3, 20, 2)\nfor n in x:\n  print(n)\n\u003e\u003e 3\n   5\n   7\n   9\n   11\n   13\n   15\n   17\n   19\n```\n\n### reversed() (Returns a reversed iterator) :\n```python\nalph = [\"a\", \"b\", \"c\", \"d\"]\nralph = reversed(alph)\nfor x in ralph:\n  print(x)\n\u003e\u003e 'd'\n   'c'\n   'b'\n   'a'\n```\n\n### round() (Rounds a numbers) :\n```python\nx = round(5.76543, 2)\nprint(x)\n\u003e\u003e 5.77\n```\n\n### slice() (Returns a slice object) :\n```python\na = (\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\")\nx = slice(2)\nprint(a[x])\n\u003e\u003e ('a', 'b')\n```\n\n### sorted() (Returns a sorted list) :\n```python\na = (\"b\", \"g\", \"a\", \"d\", \"f\", \"c\", \"h\", \"e\")\nx = sorted(a)\nprint(x)\n\u003e\u003e ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']\n```\n\n### str() (Returns a string object) :\n```python\nx = str(3.5)\nprint(x)\n\u003e\u003e \"3.5\"\n```\n\n### sum() (Sums the items of an iterator) :\n```python\na = (1, 2, 3, 4, 5)\nx = sum(a)\n\u003e\u003e 15\n```\n\n### type() (Returns the type of an object) :\n```python\na = ('apple', 'banana', 'cherry')\nb = \"Hello World\"\nc = 33\n\nx = type(a)\ny = type(b)\nz = type(c)\n\nprint(x,y,z)\n\u003e\u003e \u003cclass 'tuple'\u003e \n\u003e\u003e \u003cclass 'str'\u003e \n\u003e\u003e \u003cclass 'int'\u003e\n```\n\n\nPython-Error\n------\n![Monty Python](https://files.realpython.com/media/Python-3.12-Preview-1-Error-Messages_Watermarked.ca9ce482328d.jpg)\n**`ArithmeticError`               # Raised when an error occurs in numeric calculations**\n\n**`AssertionError`                # Raised when an assert statement fails**\n\n**`AttributeError`                # Raised when attribute reference or assignment fails**\n\n**`Exception`                     # Base class for all exceptions**\n\n**`EOFError`                      # Raised when the input() method hits an \"end of file\" condition (EOF)**\n\n**`FloatingPointError`            # Raised when a floating point calculation fails**\n\n**`GeneratorExit`                # Raised when a generator is closed (with the close() method)**\n\n**`ImportError`                   # Raised when an imported module does not exist**\n\n**`IndentationError`              # Raised when indentation is not correct**\n\n**`IndexError`                    # Raised when an index of a sequence does not exist**\n\n**`KeyError`                      # Raised when a key does not exist in a dictionary**\n\n**`KeyboardInterrupt`             # Raised when the user presses Ctrl+c, Ctrl+z or Delete**\n\n**`LookupError`                   # Raised when errors raised cant be found**\n\n**`MemoryError`                  # Raised when a program runs out of memory**\n\n**`NameError`                     # Raised when a variable does not exist**\n\n**`NotImplementedError`           # Raised when an abstract method requires an inherited class to override the method**\n\n**`OSError`                       # Raised when a system related operation causes an error**\n\n**`OverflowError`                 # Raised when the result of a numeric calculation is too large**\n\n**`ReferenceError`                # Raised when a weak reference object does not exist**\n\n**`RuntimeError`                  # Raised when an error occurs that do not belong to any specific exceptions**\n\n**`StopIteration`                 # Raised when the next() method of an iterator has no further values**\n\n**`SyntaxError`                   # Raised when a syntax error occurs**\n\n**`TabError`                      # Raised when indentation consists of tabs or spaces**\n\n**`SystemError`                   # Raised when a system error occurs**\n\n**`SystemExit`                    # Raised when the sys.exit() function is called**\n\n**`TypeError`                     # Raised when two different types are combined**\n\n**`UnboundLocalError`             # Raised when a local variable is referenced before assignment**\n\n**`UnicodeError`                  # Raised when a unicode problem occurs**\n\n**`UnicodeEncodeError`            # Raised when a unicode encoding problem occurs**\n\n**`UnicodeDecodeError`            # Raised when a unicode decoding problem occurs**\n\n**`UnicodeTranslateError`         # Raised when a unicode translation problem occurs**\n\n**`ValueError`                    # Raised when there is a wrong value in a specified data type**\n\n**`ZeroDivisionError`             # Raised when the second operator in a division is zero**\n\n\nRandom\n------\n### randrange() (Returns a random number between the given range) :\n```python\nimport random\nprint(random.randrange(3, 9))\n\u003e\u003e 4\n```\n\n### randint() (Returns a random number between the given range) :\n```python\nimport random\nprint(random.randint(3, 9))\n\u003e\u003e 9\n```\n\n### choice() (Returns a random element from the given sequence) :\n```python\nimport random\nmylist = [\"apple\", \"banana\", \"cherry\"]\nprint(random.choice(mylist))\n\u003e\u003e \"cherry\"\n```\n\n### shuffle() (Takes a sequence and returns the sequence in a random order) :\n```python\nimport random\nmylist = [\"apple\", \"banana\", \"cherry\"]\nrandom.shuffle(mylist)\nprint(mylist)\n\u003e\u003e ['cherry', 'apple', 'banana']\n```\n\n### sample() (Returns a given sample of a sequence) :\n```python\nimport random\nmylist = [\"apple\", \"banana\", \"cherry\"]\nprint(random.sample(mylist, k=2))\n\u003e\u003e ['cherry', 'banana']\n```\n\n### uniform() (Returns a random float number between two given parameters) :\n```python\nimport random\nprint(random.uniform(20, 60))\n\u003e\u003e 47.016106134431425\n```\n\n\nEnum\n------\n![Monty Python](https://files.realpython.com/media/Build-Enumerations-With-Pythons-enum_Watermarked.bbcd46a82f58.jpg)\n**Some programming languages, like Java and C++, \ninclude syntax that supports a data type known as enumerations, \nor just enums. This data type allows you to create sets of \nsemantically related constants that you can access through the enumeration itself. \nPython doesn't have a dedicated syntax for enums. However, \nthe Python standard library has an enum module that supports \nenumerations through the Enum class.**\n\n**for first this is a normal calss with normal ability :**\n```python\nclass Season(Enum):\n    SPRING = 1\n    SUMMER = 2\n    AUTUMN = 3\n    WINTER = 4\nprint(Season.SPRING)\nprint(Season.SPRING.name)\nprint(Season.SPRING.value)\nprint(type(Season.SPRING))\nprint(repr(Season.SPRING))\nprint(list(Season))\n\u003e\u003e Season.SPRING\n\u003e\u003e SPRING\n\u003e\u003e 1\n\u003e\u003e \u003cenum 'Season'\u003e\n\u003e\u003e \u003cSeason.SPRING: 1\u003e\n\u003e\u003e [\u003cSeason.SPRING: 1\u003e, \u003cSeason.SUMMER: 2\u003e, \u003cSeason.AUTUMN: 3\u003e, \u003cSeason.WINTER: 4\u003e]\n```\n\n**Or**\n\n```python\nclass Season(Enum):\n    SPRING = 1\n    SUMMER = 2\n    AUTUMN = 3\n    WINTER = 4\nprint(\"The enum member associated with value 2 is : \", Season(2).name)\nprint(\"The enum member associated with name AUTUMN is : \", Season['AUTUMN'].value)\n\u003e\u003e \"The enum member associated with value 2 is :  SUMMER\"\n\u003e\u003e \"The enum member associated with name AUTUMN is :  3\"\n```\n\n**now we use enum :**\n\n```python\nimport enum\nclass Animal(enum.Enum):\n    dog = 1\n    cat = 2\n    lion = 3\ndi = {}\ndi[Animal.dog] = 'bark'\ndi[Animal.lion] = 'roar'\nif di == {Animal.dog: 'bark', Animal.lion: 'roar'}:\n    print(\"Enum is hashed\")\nelse:\n    print(\"Enum is not hashed\")\n\u003e\u003e \"Enum is hashed\"\n```\n\n```python\nimport enum\nclass Animal(enum.Enum):\n    dog = 1\n    cat = 2\n    lion = 3\nif Animal.dog is Animal.cat:\n    print(\"Dog and cat are same animals\")\nelse:\n    print(\"Dog and cat are different animals\")\nif Animal.lion != Animal.cat:\n    print(\"Lions and cat are different\")\nelse:\n    print(\"Lions and cat are same\")\n\u003e\u003e \"Dog and cat are different animals\"\n\u003e\u003e \"Lions and cat are different\"\n```\n\n```python\nfrom enum import Enum\nclass Day(Enum):\n     MONDAY = 1\n     TUESDAY = 2\n     WEDNESDAY = 3\n     THURSDAY = 4\n     FRIDAY = 5\n     SATURDAY = 6\n     SUNDAY = 7\n\nlist(Day)\n\u003e\u003e [\n      \u003cDay.MONDAY: 1\u003e,\n      \u003cDay.TUESDAY: 2\u003e,\n      \u003cDay.WEDNESDAY: 3\u003e,\n      \u003cDay.THURSDAY: 4\u003e,\n      \u003cDay.FRIDAY: 5\u003e,\n      \u003cDay.SATURDAY: 6\u003e,\n      \u003cDay.SUNDAY: 7\u003e\n   ]\n\ntype(Day.MONDAY)\n\u003e\u003e \u003cenum 'Day'\u003e\n```\n\n```python\nfrom enum import Enum\n\nclass Season(Enum):\n    WINTER, SPRING, SUMMER, FALL = range(1, 5)\n\n\nlist(Season)\n\u003e\u003e [\n     \u003cSeason.WINTER: 1\u003e,\n     \u003cSeason.SPRING: 2\u003e,\n     \u003cSeason.SUMMER: 3\u003e,\n     \u003cSeason.FALL: 4\u003e\n   ]\n```\n\n```python\nfrom enum import Enum\n\nHTTPStatusCode = Enum(\n    value=\"HTTPStatusCode\",\n    names=[\n         (\"OK\", 200),\n         (\"CREATED\", 201),\n         (\"BAD_REQUEST\", 400),\n         (\"NOT_FOUND\", 404),\n         (\"SERVER_ERROR\", 500),],\n     )\n\nlist(HTTPStatusCode)\n\u003e\u003e [\n     \u003cHTTPStatusCode.OK: 200\u003e,\n     \u003cHTTPStatusCode.CREATED: 201\u003e,\n     \u003cHTTPStatusCode.BAD_REQUEST: 400\u003e,\n     \u003cHTTPStatusCode.NOT_FOUND: 404\u003e,\n     \u003cHTTPStatusCode.SERVER_ERROR: 500\u003e\n  ]\n```\n\n```python\nfrom enum import auto, Enum\n\nclass Day(Enum):\n     MONDAY = auto()\n     TUESDAY = auto()\n     WEDNESDAY = 3\n     THURSDAY = auto()\n     FRIDAY = auto()\n     SATURDAY = auto()\n     SUNDAY = 7\n\nlist(Day)\n\u003e\u003e [\n     \u003cDay.MONDAY: 1\u003e,\n     \u003cDay.TUESDAY: 2\u003e,\n     \u003cDay.WEDNESDAY: 3\u003e,\n     \u003cDay.THURSDAY: 4\u003e,\n     \u003cDay.FRIDAY: 5\u003e,\n     \u003cDay.SATURDAY: 6\u003e,\n     \u003cDay.SUNDAY: 7\u003e\n  ]\n```\n\n\nSystem\n----\n\n```python\nimport sys\nprint(sys.version)\n\u003e\u003e 3.11.4 (tags/v3.11.4:d2340ef, Jun  7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)]\n\nimport sys \nage = 17\nif age \u003c 18: \n    sys.exit(\"Age less than 18\")     \nelse: \n    print(\"Age is not less than 18\") \n```\n\n```python\nimport sys\nprint(sys.modules)\n```\n\n```python\n\"\"\"\nsys.argv returns a list of command line arguments passed to a Python script. \nThe item at index 0 in this list is always the name of the script. \nThe rest of the arguments are stored at the subsequent indices.\n\"\"\"\nimport sys\nprint(\"You entered: \",sys.argv[1], sys.argv[2], sys.argv[3])\n\n\u003e\u003e\u003e C:\\python36\u003e python test.py Python C# Java\n\u003e\u003e \"You entered: Python C# Java\"\n```\n\n```python\n\"\"\"\nThis is an environment variable that is a search path for all Python modules.\n\"\"\"\nimport sys\n\nprint(sys.path)\n```\n\n```python\n\"\"\"\nThis attribute displays a string containing the version number of the current Python interpreter.\n\"\"\"\n\nimport sys\n\nprint(sys.version) \n```\n\n```python\n\"\"\"\nwindows\n\"\"\"\n\nimport sys\n\nprint(sys.platform)\n```\n\n\nPath\n------\n![Monty Python](https://files.realpython.com/media/Python-3s-pathlib-Module-Taming-the-File-System_Watermarked.524352e6d4ce.jpg)\n### python path :\n```python\nfrom pathlib import Path\nprint(Path.cwd())\n\u003e\u003e \"C:\\Users\\Name\\AppData\\Local\\Programs\\Python\\Python311\"\n```\n\n### user path \n```python\n# user path :\nfrom pathlib import Path\nprint(Path.home())\n\u003e\u003e \"C:\\Users\\Name\"\n```\n\n### special path : \n```python\nfrom pathlib import Path\nprint(Path(\"C:\\\\Users\\\\Name\\\\Desktop\\\\Pic\"))\n\u003e\u003e WindowsPath('C:\\\\Users\\\\Name\\\\Desktop\\\\Pic')\n```\n\n### Picking Out Components of a Path : \n```python\nfrom pathlib import Path\npath = Path(\"C:\\\\Users\\\\Name\\\\realpython\\\\test.md\")\nprint(path)\n\u003e\u003e WindowsPath('C:/Users/Name/realpython/test.md')\n\nprint(path.name)\n\u003e\u003e 'test.md'\n\nprint(path.stem)\n\u003e\u003e 'test'\n\nprint(path.suffix)\n\u003e\u003e '.md'\n\nprint(path.anchor)\n\u003e\u003e 'C:\\\\'\n\nprint(path.parent)\n\u003e\u003e WindowsPath('C:/Users/Name/realpython\")\n\nprint(path.parent.parent)\n\u003e\u003e WindowsPath('C:/Users/Name')\n```\n\n### Reading and Writing Files : \n```python\nfrom pathlib import Path\npath = Path(\"C:\\\\Users\\\\NAJAFI\\\\Desktop\\\\Pic.txt\")\nwith path.open(mode=\"r\", encoding=\"utf-8\") as md_file:\n    content = md_file.read()\n    print(content)\n\u003e\u003e \"hello\"\n```\n* **`.read_text()` opens the path in text mode and returns the contents as a string.**\n* **`.read_bytes()` opens the path in binary mode and returns the contents as a byte string.**\n* **`.write_text()` opens the path and writes string data to it.**\n* **`.write_bytes()` opens the path in binary mode and writes data to it.**\n\n\n### Renaming Files : \n```python\nfrom pathlib import Path\ntxt_path = Path(\"/home/gahjelle/realpython/hello.txt\")\nPrint(txt_path)\n\u003e\u003e PosixPath(\"/home/gahjelle/realpython/hello.txt\")\n\nmd_path = txt_path.with_suffix(\".md\")\n\u003e\u003e PosixPath('/home/gahjelle/realpython/hello.md')\ntxt_path.replace(md_path)\n```\n\n### Copying Files : \n```python\nfrom pathlib import Path\nsource = Path(\"shopping_list.md\")\ndestination = source.with_stem(\"shopping_list_02\")\ndestination.write_bytes(source.read_bytes()) # .read_bytes() to read the content of source and then write this content to destination using .write_bytes().\n```\n\n### Moving Files : \n```python\nfrom pathlib import Path\nsource = Path(\"hello.py\")\ndestination = Path(\"goodbye.py\")\nif not destination.exists():\n    source.replace(destination)\n```\n\n### Create Files : \n```python\nfrom pathlib import Path\nfilename = Path(\"C:\\\\Users\\\\Name\\\\Desktop\\\\h.txt\")\nfilename.exists()\n\u003e\u003e False\nfilename.touch()\nfilename.exists()\n\u003e\u003e True\n```\n\n### copy and insert the file :\n```python\nimport shutil, os\nfrom pathlib import Path\nprint(p)\nshutil.copy('C:\\\\Users\\\\Name\\\\Desktop\\\\h.txt','C:\\\\Users\\\\Name\\\\Desktop\\\\0')\n```\n\n### move file :\n```python\nimport shutil\nshutil.move('C:\\\\Users\\\\Name\\\\Desktop\\\\h.txt','C:\\\\Users\\\\Name\\\\Desktop\\\\0')\n```\n\nPickle\n------\n![Monty Python](https://files.realpython.com/media/Object-Serialization-With-the-Python-Pickle-Module_Watermarked.8e4667c2f71f.jpg)\n\n**Python pickle module is used for serializing and de-serializing a Python object structure. \nAny object in Python can be pickled so that it can be saved on disk. \nWhat Pickle does is it “serializes” the object first before writing it to a file. \nPickling is a way to convert a Python object (list, dictionary, etc.) into a character stream. \nThe idea is that this character stream contains all the information necessary to reconstruct the object in another Python script. \nIt provides a facility to convert any Python object to a byte stream. \nThis Byte stream contains all essential information about the object so that it can be reconstructed, or “unpickled” and get back into its original form in any Python.**\n\n**this is a normal pickle in this file :**\n\n```python\nimport pickle\nOmkar = {'key' : 'Omkar', 'name' : 'Omkar Pathak', \n'age' : 21, 'pay' : 40000}\n\nJagdish = {'key' : 'Jagdish', 'name' : 'Jagdish Pathak',\n'age' : 50, 'pay' : 50000}\n \ndb = {}\ndb['Omkar'] = Omkar\ndb['Jagdish'] = Jagdish\n\nb = pickle.dumps(db)   \n\nmyEntry = pickle.loads(b)\nprint(myEntry)\n\u003e\u003e {'Omkar': {'key': 'Omkar', 'name': 'Omkar Pathak', 'age': 21, 'pay': 40000}, 'Jagdish': {'key': 'Jagdish', 'name': 'Jagdish Pathak', 'age': 50, 'pay': 50000}}\n```\n\n**now we want insert Python objects in an Independent file :**\n\n```python\nimport pickle\n \ndef storeData():\n    # initializing data to be stored in db\n    Omkar = {'key' : 'Omkar', 'name' : 'Omkar Pathak',\n    'age' : 21, 'pay' : 40000}\n    Jagdish = {'key' : 'Jagdish', 'name' : 'Jagdish Pathak',\n    'age' : 50, 'pay' : 50000}\n \n    # database\n    db = {}\n    db['Omkar'] = Omkar\n    db['Jagdish'] = Jagdish\n     \n    # Its important to use binary mode\n    dbfile = open('examplePickle', 'ab')\n     \n    # source, destination\n    pickle.dump(db, dbfile)                    \n    dbfile.close()\n \ndef loadData():\n    # for reading also binary mode is important\n    dbfile = open('examplePickle', 'rb')    \n    db = pickle.load(dbfile)\n    for keys in db:\n        print(keys, '=\u003e', db[keys])\n    dbfile.close()\n \nif __name__ == '__main__':\n    storeData()\n    loadData()\n\n\u003e\u003e Omkar =\u003e {'key': 'Omkar', 'name': 'Omkar Pathak', 'age': 21, 'pay': 40000}\n   Jagdish =\u003e {'key': 'Jagdish', 'name': 'Jagdish Pathak', 'age': 50, 'pay': 50000}\n```\n\n**now we can see :**\n\n```python\nimport pickle\n# for reading also binary mode is important\ndbfile = open('examplePickle', 'rb')    \ndb = pickle.load(dbfile)\nfor keys in db:\n    print(keys, '=\u003e', db[keys])\ndbfile.close()\n\n\u003e\u003e Omkar =\u003e {'key': 'Omkar', 'name': 'Omkar Pathak', 'age': 21, 'pay': 40000}\n   Jagdish =\u003e {'key': 'Jagdish', 'name': 'Jagdish Pathak', 'age': 50, 'pay': 50000}\n```\n\nCollections\n------\n![Monty Python](https://files.realpython.com/media/Pythons-Collections-Module_Watermarked.31248400c167.jpg)\n**The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc.**\n\n**Counter :**\n```python\nfrom collections import Counter  \n# With sequence of items   \nprint(Counter(['B','B','A','B','C','A','B','B','A','C'])) \n\u003e\u003e Counter({'B': 5, 'A': 3, 'C': 2})\n\n# with dictionary  \nprint(Counter({'A':3, 'B':5, 'C':2})) \n\u003e\u003e Counter({'B': 5, 'A': 3, 'C': 2})\n\n# with keyword arguments  \nprint(Counter(A=3, B=5, C=2))\n\u003e\u003e Counter({'B': 5, 'A': 3, 'C': 2})\n```\n\n```python\nfrom collections import Counter\n\nCounter(\"mississippi\")\n\u003e\u003e Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})\n```\n\n```python\nfrom collections import Counter\n\nletters = Counter(\"mississippi\")\nletters\n\u003e\u003e Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})\n\n# Update the counts of m and i\nletters.update(m=3, i=4)\nletters\n\u003e\u003e Counter({'i': 8, 'm': 4, 's': 4, 'p': 2})\n\n# Add a new key-count pair\nletters.update({\"a\": 2})\nletters\n\u003e\u003e Counter({'i': 8, 'm': 4, 's': 4, 'p': 2, 'a': 2})\n\n# Update with another counter\nletters.update(Counter([\"s\", \"s\", \"p\"]))\nletters\n\u003e\u003e Counter({'i': 8, 's': 6, 'm': 4, 'p': 3, 'a': 2})\n```\n\n```python\nfrom collections import Counter\n\nletters = Counter(\"mississippi\")\nletters[\"a\"]\n\u003e\u003e 0\n```\n\n```python\nfrom collections import Counter\n\nCounter([1, 1, 2, 3, 3, 3, 4])\n\u003e\u003e Counter({3: 3, 1: 2, 2: 1, 4: 1})\n```\n\n**namedtuple :**\n```python\nfrom collections import namedtuple \n    \n# Declaring namedtuple()  \nStudent = namedtuple('Student',['name','age','DOB'])  \n    \n# Adding values  \nS = Student('Nandini','19','2541997')\n    \n# Access using index  \nprint (\"The Student age using index is : \",end =\"\")  \nprint (S[1])  \n\u003e\u003e \"The Student age using index is :\" 19\n    \n# Access using name   \nprint (\"The Student name using keyname is : \",end =\"\")  \nprint (S.name)\n\u003e\u003e \"The Student name using keyname is :\" \"Nandini\"\n```\n\n```python\nfrom collections import namedtuple\n\n# Use a list of strings as field names\nPoint = namedtuple(\"Point\", [\"x\", \"y\"])\npoint = Point(2, 4)\npoint\n\u003e\u003e Point(x=2, y=4)\n\n# Access the coordinates\npoint.x\n\u003e\u003e 2\npoint.y\n\u003e\u003e 4\npoint[0]\n\u003e\u003e 2\n\n# Use a generator expression as field names\nPoint = namedtuple(\"Point\", (field for field in \"xy\"))\nPoint(2, 4)\n\u003e\u003e Point(x=2, y=4)\n\n# Use a string with comma-separated field names\nPoint = namedtuple(\"Point\", \"x, y\")\nPoint(2, 4)\n\u003e\u003e Point(x=2, y=4)\n\n# Use a string with space-separated field names\nPoint = namedtuple(\"Point\", \"x y\")\nPoint(2, 4)\n\u003e\u003e Point(x=2, y=4)\n```\n\n```python\nfrom collections import namedtuple\n\n# Define default values for fields\nPerson = namedtuple(\"Person\", \"name job\", defaults=[\"Python Developer\"])\nperson = Person(\"Jane\")\nperson\n\u003e\u003e Person(name='Jane', job='Python Developer')\n\n# Create a dictionary from a named tuple\nperson._asdict()\n\u003e\u003e {'name': 'Jane', 'job': 'Python Developer'}\n\n# Replace the value of a field\nperson = person._replace(job=\"Web Developer\")\nperson\n\u003e\u003e Person(name='Jane', job='Web Developer')\n```\n\n**deque :**\n```python\nfrom collections import deque \n    \n# Declaring deque \nqueue = deque(['name','age','DOB'])  \n    \nprint(queue)\n\u003e\u003e deque(['name', 'age', 'DOB'])\n```\n\n```python\nfrom collections import deque  \n    \n# initializing deque  \nde = deque([1,2,3])  \n    \n# using append() to insert element at right end   \n# inserts 4 at the end of deque  \nde.append(4)  \n    \n# printing modified deque  \nprint (\"The deque after appending at right is : \")  \nprint (de)  \n\u003e\u003e \"The deque after appending at right is :\" \n   deque([1, 2, 3, 4])\n    \n# using appendleft() to insert element at left end   \n# inserts 6 at the beginning of deque  \nde.appendleft(6)  \n    \n# printing modified deque  \nprint (\"The deque after appending at left is : \")  \nprint (de)\n\u003e\u003e \"The deque after appending at left is :\" \n   deque([6, 1, 2, 3, 4])\n```\n\n```python\nfrom collections import deque \n  \n# initializing deque  \nde = deque([6, 1, 2, 3, 4]) \n  \n# using pop() to delete element from right end   \n# deletes 4 from the right end of deque  \nde.pop()  \n    \n# printing modified deque  \nprint (\"The deque after deleting from right is : \")  \nprint (de)  \n\u003e\u003e \"The deque after deleting from right is : \"\n   deque([6, 1, 2, 3])\n    \n# using popleft() to delete element from left end   \n# deletes 6 from the left end of deque  \nde.popleft()  \n    \n# printing modified deque  \nprint (\"The deque after deleting from left is : \")  \nprint (de)\n\u003e\u003e \"The deque after deleting from left is : \"\n   deque([1, 2, 3])\n```\n\n**OrderedDict :**\n```python\nfrom collections import OrderedDict  \n    \nprint(\"This is a Dict:\\n\")  \nd = {}  \nd['a'] = 1\nd['b'] = 2\nd['c'] = 3\nd['d'] = 4\n    \nfor key, value in d.items():  \n    print(key, value)  \n\n\u003e\u003e \"This is a Dict:\"\n\u003e\u003e a 1\n   b 2\n   c 3\n   d 4\n```\n\n```python\nfrom collections import OrderedDict  \n\nprint(\"\\nThis is an Ordered Dict:\\n\")  \nod = OrderedDict()  \nod['b'] = 1\nod['d'] = 2\nod['c'] = 3\nod['a'] = 4\n\nfor key, value in od.items():  \n    print(key, value)\nprint(od)\n\n\u003e\u003e \"This is an Ordered Dict:\"\n\u003e\u003e a 1\n   b 2\n   c 3\n   d 4\n```\n\n```python\nfrom collections import OrderedDict\n\nlife_stages = OrderedDict()\n\nlife_stages[\"childhood\"] = \"0-9\"\nlife_stages[\"adolescence\"] = \"9-18\"\nlife_stages[\"adulthood\"] = \"18-65\"\nlife_stages[\"old\"] = \"+65\"\n\nfor stage, years in life_stages.items():\n     print(stage, \"-\u003e\", years)\n\u003e\u003e childhood -\u003e 0-9\n\u003e\u003e adolescence -\u003e 9-18\n\u003e\u003e adulthood -\u003e 18-65\n\u003e\u003e old -\u003e +65\n```\n\n**defaultdict :**\n```python\nfrom collections import defaultdict  \n     \n# Defining the dict  \nd = defaultdict(int)  \n     \nL = [1, 2, 3, 4, 2, 4, 1, 2]  \n     \n# Iterate through the list  \n# for keeping the count  \nfor i in L:  \n    # The default value is 0  \n    # so there is no need to   \n    # enter the key first  \n    d[i] += 1\n         \nprint(d)\n\u003e\u003e defaultdict(\u003cclass 'int'\u003e, {1: 2, 2: 3, 3: 1, 4: 2})\n```\n\n```python\nfrom collections import defaultdict  \n    \n# Defining a dict  \nd = defaultdict(list)  \n    \nfor i in range(5):  \n    d[i].append(i)  \n        \nprint(\"Dictionary with values as list:\")  \nprint(d)\n\u003e\u003e \"Dictionary with values as list:\"\n\u003e\u003e defaultdict(\u003cclass ‘list’\u003e, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})\n```\n\n```python\nfrom collections import defaultdict\n\ncounter = defaultdict(int)\ncounter\n\u003e\u003e defaultdict(\u003cclass 'int'\u003e, {})\ncounter[\"dogs\"]\n\u003e\u003e 0\ncounter\n\u003e\u003e defaultdict(\u003cclass 'int'\u003e, {'dogs': 0})\n\ncounter[\"dogs\"] += 1\ncounter[\"dogs\"] += 1\ncounter[\"dogs\"] += 1\ncounter[\"cats\"] += 1\ncounter[\"cats\"] += 1\ncounter\n\u003e\u003e defaultdict(\u003cclass 'int'\u003e, {'dogs': 3, 'cats': 2})\n```\n\n**ChainMap :**\n```python\nfrom collections import ChainMap  \n\nd1 = {'a': 1, 'b': 2} \nd2 = {'c': 3, 'd': 4} \nd3 = {'e': 5, 'f': 6} \n  \n# Defining the chainmap  \nc = ChainMap(d1, d2, d3)    \nprint(c)\n\u003e\u003e ChainMap({'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6})\n```\n\n```python\nfrom collections import ChainMap  \n\nd1 = {","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhafez-cs%2Fpython-handbook","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhafez-cs%2Fpython-handbook","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhafez-cs%2Fpython-handbook/lists"}