{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [], "authorship_tag": "ABX9TyNcFlp7YVayvq9znSKH6iqf", "include_colab_link": true }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "4sj2Aei4A5l3" }, "outputs": [], "source": [] }, { "cell_type": "markdown", "source": [ "# **Python syntax and semantics**\n", "\n", "The syntax of the Python programming language is the set of rules that defines how a Python program will be written and interpreted (by both the runtime system and by human readers).\n", "\n", "\"There should be one— and preferably only one —obvious way to do it\", from the Zen of Python.\n", "\n", "Python's syntax is simple and consistent, adhering to the principle that \"There should be one—and preferably only one—obvious way to do it.\"" ], "metadata": { "id": "ErkyfwegIT-0" } }, { "cell_type": "markdown", "source": [ "Keywords\n", "Python 3 has 35 keywords or reserved words; they cannot be used as identifiers.\n", "\n", "and as assert async await break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield\n", "\n", "In addition, Python 3 also has 4 soft keywords, including type added in Python 3.12. Unlike regular hard keywords, soft keywords are reserved words only in the limited contexts where interpreting them as keywords would make syntactic sense. These words can be used as identifiers elsewhere, in other words, match and case are valid names for functions and variables.\n", "\n", "_\n", "case\n", "match\n", "type" ], "metadata": { "id": "fNOcF_fCIwCk" } }, { "cell_type": "markdown", "source": [ "# **Function annotations**\n", "Function annotations (type hints) are defined in PEP 3107.[8] They allow attaching data to the arguments and return of a function. The behaviour of annotations is not defined by the language, and is left to third party frameworks. For example, a library could be written to handle static typing:" ], "metadata": { "id": "hFOghG_DJRsl" } }, { "cell_type": "code", "source": [ "def haul(item: Haulable, *vargs: PackAnimal) -> Distance:\n", " # implementation here" ], "metadata": { "id": "GP9agDjiJUL1" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Modules and import statements**\n", "In Python, code is organized into files called modules, and namespaces are defined by the individual modules. Since modules can be contained in hierarchical packages, then namespaces are hierarchical too.[9][10] In general when a module is imported then the names defined in the module are defined via that module's namespace, and are accessed in from the calling modules by using the fully qualified name." ], "metadata": { "id": "yvYIti5iJXcs" } }, { "cell_type": "code", "source": [ "# assume ModuleA defines two functions : func1() and func2() and one class : Class1\n", "import ModuleA\n", "\n", "ModuleA.func1()\n", "ModuleA.func2()\n", "a: ModuleA.Class1 = Modulea.Class1()" ], "metadata": { "id": "1Uyv0rAhJXsV" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Entry point**\n", "A pseudo-entry point can be created by the following idiom, which relies on the internal variable __name__ being set to __main__ when a program is executed, but not when it is imported as a module (in which case it is instead set to the module name); there are many variants of this structur" ], "metadata": { "id": "KiqITmJSJX2F" } }, { "cell_type": "code", "source": [ "import sys\n", "\n", "def main(argv: List[str]) -> int:\n", " argc: int = len(argv) # get length of argv\n", " n: int = int(argv[1])\n", " print(n + 1)\n", " return 0\n", "\n", "if __name__ == \"__main__\":\n", " sys.exit(main(sys.argv))" ], "metadata": { "id": "C3SzVrmxJX-M" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Indentation**\n", "Python uses whitespace to delimit control flow blocks (following the off-side rule). Python borrows this feature from its predecessor ABC: instead of punctuation or keywords, it uses indentation to indicate the run of a block.\n", "\n", "In so-called \"free-format\" languages – that use the block structure derived from ALGOL – blocks of code are set off with braces ({ }) or keywords. In most coding conventions for these languages, programmers conventionally indent the code within a block, to visually set it apart from the surrounding code.\n", "\n", "A recursive function named foo, which is passed a single parameter, x, and if the parameter is 0 will call a different function named bar and otherwise will call baz, passing x, and also call itself recursively, passing x-1 as the parameter, could be implemented like this in Python:" ], "metadata": { "id": "sOjxX74OJYHN" } }, { "cell_type": "code", "source": [ "def foo(x: int) -> None:\n", " if x == 0:\n", " bar()\n", " else:\n", " baz(x)\n", " foo(x - 1)" ], "metadata": { "id": "Y9q1vdkyJYPl" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Data structures**\n", "Python is a dynamically-typed language, Python values, not variables, carry type information. All variables in Python hold references to objects, and these references are passed to functions. Some people (including Python creator Guido van Rossum himself) have called this parameter-passing scheme \"call by object reference\". An object reference means a name, and the passed reference is an \"alias\", i.e. a copy of the reference to the same object, just as in C/C++. The object's value may be changed in the called function with the \"alias\"" ], "metadata": { "id": "s8BlDLZCJYW1" } }, { "cell_type": "code", "source": [ "my_list: List[str] = [\"a\", \"b\", \"c\"]\n", "def my_func(l: List[str]) -> None:\n", " l.append(\"x\")\n", " print(l)\n", "\n", "print(my_func(my_list))\n", "# prints ['a', 'b', 'c', 'x']\n", "print(my_list)\n", "# prints ['a', 'b', 'c', 'x']" ], "metadata": { "id": "NYKa_D_BJYfd" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Base types**\n", "Python has a broad range of basic data types. Alongside conventional integer and floating-point arithmetic, it transparently supports arbitrary-precision arithmetic, complex numbers, and decimal numbers.\n", "\n", "Python supports a wide variety of string operations. Strings in Python are immutable, meaning that string operations, such as replacement of characters, return a new string; in other programming languages the string might be altered in place. Performance considerations sometimes push for using special techniques in programs that modify strings intensively, such as joining character arrays into strings only as needed." ], "metadata": { "id": "vNI8f0StJYnt" } }, { "cell_type": "markdown", "source": [ "# **Collection types**\n", "One of the very useful aspects of Python is the concept of collection (or container) types. In general a collection is an object that contains other objects in a way that is easily referenced or indexed. Collections come in two basic forms: sequences and mappings.\n", "\n", "The ordered sequential types are lists (dynamic arrays), tuples, and strings. All sequences are indexed positionally (0 through length - 1) and all but strings can contain any type of object, including multiple types in the same sequence. Both strings and tuples are immutable, making them perfect candidates for dictionary keys (see below). Lists, on the other hand, are mutable; elements can be inserted, deleted, modified, appended, or sorted in-place.\n", "\n", "**Mappings**, on the other hand, are (often unordered) types implemented in the form of dictionaries which \"map\" a set of immutable keys to corresponding elements (much like a mathematical function). For example, one could define a dictionary having a string \"toast\" mapped to the integer 42 or vice versa. The keys in a dictionary must be of an immutable Python type, such as an integer or a string, because they are implemented via a hash function. This makes for much faster lookup times, but requires keys to remain unchanged.\n", "\n", "**Dictionaries** are central to the internals of Python as they reside at the core of all objects and classes: the mappings between variable names (strings) and the values which the names reference are stored as dictionaries (see Object system). Since these dictionaries are directly accessible (via an object's __dict__ attribute), metaprogramming is a straightforward and natural process in Python.\n", "\n", "A **set** collection type is an unindexed, unordered collection that contains no duplicates, and implements set theoretic operations such as union, intersection, difference, symmetric difference, and subset testing. There are two types of sets: set and frozenset, the only difference being that set is mutable and frozenset is immutable. Elements in a set must be hashable. Thus, for example, a frozenset can be an element of a regular set whereas the opposite is not true." ], "metadata": { "id": "17mQXM7kKFp1" } }, { "cell_type": "markdown", "source": [ "# **Object system**\n", "In Python, everything is an object, even classes. Classes, as objects, have a class, which is known as their metaclass. Python also supports multiple inheritance and mixins.\n", "\n", "The language supports extensive introspection of types and classes. Types can be read and compared: Types are instances of the object type. The attributes of an object can be extracted as a dictionary.\n", "\n", "Operators can be overloaded in Python by defining special member functions – for instance, defining a method named __add__ on a class permits one to use the + operator on objects of that class." ], "metadata": { "id": "71YlusaOKOZ9" } }, { "cell_type": "markdown", "source": [ "# **Literals**\n", "**Strings**\n", "Python has various kinds of string literals." ], "metadata": { "id": "_RTrZ-t4KSld" } }, { "cell_type": "code", "source": [ "num = 101\n", "printer = \"Epson 2003\"\n", "\n", "print(f\"I just printed {num} pages to the printer {printer}\")\n", "\n", "print(\"I just printed {} pages to the printer {}\".format(num, printer))\n", "print(\"I just printed {0} pages to the printer {1}\".format(num, printer))\n", "print(\"I just printed {a} pages to the printer {b}\".format(a=num, b=printer))\n", "\n", "print(\"I just printed %s pages to the printer %s\" % (num, printer))\n", "print(\"I just printed %(a)s pages to the printer %(b)s\" % {\"a\": num, \"b\": printer})" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "GRwJBfLGJYu9", "outputId": "8a4f12fd-ba47-455f-dc5e-a8759dd9ab46" }, "execution_count": 2, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "I just printed 101 pages to the printer Epson 2003\n", "I just printed 101 pages to the printer Epson 2003\n", "I just printed 101 pages to the printer Epson 2003\n", "I just printed 101 pages to the printer Epson 2003\n", "I just printed 101 pages to the printer Epson 2003\n", "I just printed 101 pages to the printer Epson 2003\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Multi-line string literals**\n", "There are also multi-line strings, which begin and end with a series of three single or double quotes and function like here documents in Perl and Ruby.\n", "\n", "A simple example with variable interpolation (using the format method) is:" ], "metadata": { "id": "Ie-gHv0_KmAu" } }, { "cell_type": "code", "source": [ "print('''Dear {recipient},\n", "\n", "I wish you to leave Sunnydale and never return.\n", "\n", "Not Quite Love,\n", "{sender}\n", "'''.format(sender=\"Buffy the Vampire Slayer\", recipient=\"Spike\"))" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Jw52wRjYKnTt", "outputId": "c01b9415-f96b-418d-feee-61209b1cc435" }, "execution_count": 3, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Dear Spike,\n", "\n", "I wish you to leave Sunnydale and never return.\n", "\n", "Not Quite Love,\n", "Buffy the Vampire Slayer\n", "\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Raw strings**\n", "Finally, all of the previously mentioned string types come in \"raw\" varieties (denoted by placing a literal r before the opening quote), which do no backslash-interpolation and hence are very useful for regular expressions; compare \"@-quoting\" in C#. Raw strings were originally included specifically for regular expressions. Due to limitations of the tokenizer, raw strings may not have a trailing backslash.[20] Creating a raw string holding a Windows path ending with a backslash requires some variety of workaround (commonly, using forward slashes instead of backslashes, since Windows accepts both)." ], "metadata": { "id": "Zh3h3A8nKnan" } }, { "cell_type": "code", "source": [ "'''\n", "# A Windows path, even raw strings cannot end in a backslash\n", "win_path: str = r\"C:\\Foo\\Bar\\Baz\\\"\n", "\n", "# Error:\n", "# File \"\", line 1\n", "# win_path: str = r\"C:\\Foo\\Bar\\Baz\\\"\n", "# ^\n", "# SyntaxError: EOL while scanning string literal\n", "\n", "dos_path: str = r\"C:\\Foo\\Bar\\Baz\\ \" # avoids the error by adding\n", "print(dos_path.rstrip()) # and removing trailing space\n", "# prints('C:\\\\Foo\\\\Bar\\\\Baz\\\\')\n", "\n", "quoted_dos_path: str = r'\"{}\"'.format(dos_path)\n", "print(quoted_dos_path)\n", "# prints '\"C:\\\\Foo\\\\Bar\\\\Baz\\\\ \"'\n", "\n", "# A regular expression matching a quoted string with possible backslash quoting\n", "print(re.match(r'\"(([^\"\\\\]|\\\\.)*)\"', quoted_dos_path).group(1).rstrip())\n", "# prints 'C:\\\\Foo\\\\Bar\\\\Baz\\\\'\n", "\n", "code: str = 'foo(2, bar)'\n", "# Reverse the arguments in a two-arg function call\n", "print(re.sub(r'\\(([^,]*?),([^ ,]*?)\\)', r'(\\2, \\1)', code))\n", "# prints 'foo(2, bar)'\n", "# Note that this won't work if either argument has parens or commas in it.\n", "'''" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 192 }, "id": "iskZK4e0Knhd", "outputId": "8b43f518-9f0e-450c-f5fe-4dba8519d5fe" }, "execution_count": 5, "outputs": [ { "output_type": "stream", "name": "stderr", "text": [ "<>:3: SyntaxWarning: invalid escape sequence '\\F'\n", "<>:3: SyntaxWarning: invalid escape sequence '\\F'\n", "/tmp/ipython-input-332923834.py:3: SyntaxWarning: invalid escape sequence '\\F'\n", " win_path: str = r\"C:\\Foo\\Bar\\Baz\\\"\n" ] }, { "output_type": "execute_result", "data": { "text/plain": [ "'\\n# A Windows path, even raw strings cannot end in a backslash\\nwin_path: str = r\"C:\\\\Foo\\\\Bar\\\\Baz\"\\n\\n# Error:\\n# File \"\", line 1\\n# win_path: str = r\"C:\\\\Foo\\\\Bar\\\\Baz\"\\n# ^\\n# SyntaxError: EOL while scanning string literal\\n\\ndos_path: str = r\"C:\\\\Foo\\\\Bar\\\\Baz\\\\ \" # avoids the error by adding\\nprint(dos_path.rstrip()) # and removing trailing space\\n# prints(\\'C:\\\\Foo\\\\Bar\\\\Baz\\\\\\')\\n\\nquoted_dos_path: str = r\\'\"{}\"\\'.format(dos_path)\\nprint(quoted_dos_path)\\n# prints \\'\"C:\\\\Foo\\\\Bar\\\\Baz\\\\ \"\\'\\n\\n# A regular expression matching a quoted string with possible backslash quoting\\nprint(re.match(r\\'\"(([^\"\\\\]|\\\\.)*)\"\\', quoted_dos_path).group(1).rstrip())\\n# prints \\'C:\\\\Foo\\\\Bar\\\\Baz\\\\\\'\\n\\ncode: str = \\'foo(2, bar)\\'\\n# Reverse the arguments in a two-arg function call\\nprint(re.sub(r\\'\\\\(([^,]*?),([^ ,]*?)\\\\)\\', r\\'(\\x02, \\x01)\\', code))\\n# prints \\'foo(2, bar)\\'\\n# Note that this won\\'t work if either argument has parens or commas in it.\\n'" ], "application/vnd.google.colaboratory.intrinsic+json": { "type": "string" } }, "metadata": {}, "execution_count": 5 } ] }, { "cell_type": "markdown", "source": [ "# **Concatenation of adjacent string literals**\n", "String literals appearing contiguously and only separated by whitespace (including new lines using backslashes), are allowed and are aggregated into a single longer string." ], "metadata": { "id": "7uu6OHPAKnnt" } }, { "cell_type": "code", "source": [ "title: str = \"One Good Turn: \" \\\n", " 'A Natural History of the Screwdriver and the Screw'" ], "metadata": { "id": "0ZinzbHCKntV" }, "execution_count": 6, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Unicode**\n", "Since Python 3.0, the default character set is UTF-8 both for source code and the interpreter. In UTF-8, unicode strings are handled like traditional byte strings. This example will work:" ], "metadata": { "id": "Hcv1wyQmKn3F" } }, { "cell_type": "code", "source": [ "s: str = \"Zahid\" # Hello in Greek\n", "print(s)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "lUTaQuW2Kn8t", "outputId": "018bc878-723f-4b6f-f716-d9050dad1fc5" }, "execution_count": 8, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Zahid\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Numbers**\n", "Numeric literals in Python are of the normal sort, e.g. 0, -1, 3.4, 3.5e-8.\n", "\n", "Python has arbitrary-length integers and automatically increases their storage size as necessary. Prior to Python 3, there were two kinds of integral numbers: traditional fixed size integers and \"long\" integers of arbitrary size. The conversion to \"long\" integers was performed automatically when required, and thus the programmer usually did not have to be aware of the two integral types. In newer language versions the distinction is completely gone and all integers behave like arbitrary-length integers.\n", "\n", "Python supports normal floating point numbers, which are created when a dot is used in a literal (e.g. 1.1), when an integer and a floating point number are used in an expression, or as a result of some mathematical operations (\"true division\" via the / operator, or exponentiation with a negative exponent).\n", "\n", "Python also supports complex numbers natively. The imaginary component of a complex number is indicated with the J or j suffix, e.g. 3 + 4j." ], "metadata": { "id": "La62AVznKoCl" } }, { "cell_type": "code", "source": [ "a = 5\n", "print(a)" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6sEOufObKoH9", "outputId": "aa362b82-6bb9-48b1-b3b8-c15cebf53ada" }, "execution_count": 9, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "5\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Lists, tuples, sets, dictionaries**\n", "Python has syntactic support for the creation of container types.\n", "\n", "Lists (class list) are mutable sequences of items of arbitrary types, and can be created either with the special syntax" ], "metadata": { "id": "uvjWD3eSKoOl" } }, { "cell_type": "code", "source": [ "my_list: List[Union[int, str]] = [1, 2, 3, \"a dog\"]\n", "my_second_list: List[int] = []\n", "my_second_list.append(4)\n", "my_second_list.append(5)\n", "\n", "\n", "my_tuple: Tuple[Union[int, str]] = 1, 2, 3, \"four\"\n", "my_tuple: Tuple[Union[int, str]] = (1, 2, 3, \"four\")\n", "\n", "\n", "\n", "my_set: Set[Any] = {0, (), False}\n", "\n", "\n", "my_dictionary: Dict[Any, Any] = {\"key 1\": \"value 1\", 2: 3, 4: []}" ], "metadata": { "id": "rdM0kBWWLjVm" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Operators**\n", "**Arithmetic**\n", "Python includes the +, -, *, / (\"true division\"), // (floor division), % (modulus), and ** (exponentiation) operators, with their usual mathematical precedence." ], "metadata": { "id": "QljM21p8Ljed" } }, { "cell_type": "code", "source": [ "print(4 / 2)\n", "# prints 2.0" ], "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "s2i8JpWfLjlW", "outputId": "765afb18-a073-4fe3-c371-387a87891659" }, "execution_count": 10, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "2.0\n" ] } ] }, { "cell_type": "markdown", "source": [ "# **Comparison operators**\n", "The comparison operators, i.e. ==, !=, <, >, <=, >=, is, is not, in and not in are used on all manner of values. Numbers, strings, sequences, and mappings can all be compared. In Python 3, disparate types (such as a str and an int) do not have a consistent relative ordering, and attempts to compare these types raises a TypeError exception. While it was possible to compare disparate types in Python 2 (for example, whether a string was greater-than or less-than an integer), the ordering was undefined; this was considered a historical design quirk and was ultimately removed in Python 3.\n", "\n", "# **Logical operators**\n", "In all versions of Python, boolean operators treat zero values or empty values such as \"\", 0, None, 0.0, [], and {} as false, while in general treating non-empty, non-zero values as true. The boolean values True and False were added to the language in Python 2.2.1 as constants (subclassed from 1 and 0) and were changed to be full blown keywords in Python 3. The binary comparison operators such as == and > return either True or False." ], "metadata": { "id": "o2zOYmSuLjre" } }, { "cell_type": "code", "source": [], "metadata": { "id": "32vlqCjeLjw1" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Functional programming**\n", "A strength of Python is the availability of a functional programming style, which makes working with lists and other collections much more straightforward.\n", "\n", "# **Comprehensions**\n", "Main article: List comprehension\n", "One such construction is the list comprehension, which can be expressed with the following format:" ], "metadata": { "id": "QtL7d-lrLj29" } }, { "cell_type": "code", "source": [ "List[Any] = [mapping_expression for element in source_list if filter_expression]\n", "\n", "\n", "powers_of_two: List[int] = [2 ** n for n in range(1, 6)]\n", "\n", "\n", "T: TypeVar = TypeVar(\"T\")\n", "\n", "def qsort(l: List[T]) -> List[T]:\n", " if l == []:\n", " return []\n", " pivot: T = l[0]\n", " return (qsort([x for x in l[1:] if x < pivot]) +\n", " [pivot] +\n", " qsort([x for x in l[1:] if x >= pivot]))" ], "metadata": { "id": "7OxZovQULj_G" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **First-class functions**\n", "In Python, functions are first-class objects that can be created and passed around dynamically." ], "metadata": { "id": "oUgSmAxvLkFn" } }, { "cell_type": "code", "source": [ "f: Callable[[int], int] = lambda x: x**2\n", "f(5)" ], "metadata": { "id": "9Owy5f-yLkLn" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Closures**\n", "Python has had support for lexical closures since version 2.2. Here's an example function that returns a function that approximates the derivative of the given function:" ], "metadata": { "id": "bhI8oVe5LkR9" } }, { "cell_type": "code", "source": [ "def derivative(f: Callable[[float], float], dx: float):\n", " \"\"\"Return a function that approximates the derivative of f\n", " using an interval of dx, which should be appropriately small.\n", " \"\"\"\n", " def function(x: float) -> float:\n", " return (f(x + dx) - f(x)) / dx\n", " return function\n", "\n", "def foo(a: int, b: int) -> None:\n", " print(f\"a: {a}\")\n", " print(f\"b: {b}\")\n", " def bar(c: int) -> None:\n", " b = c\n", " print(f\"b*: {b}\")\n", " bar(a)\n", " print(f\"b: {b}\")\n", "\n", "print(foo(1, 2))\n", "# prints:\n", "# a: 1\n", "# b: 2\n", "# b*: 1\n", "# b: 2" ], "metadata": { "id": "nAvVUAh1LkX4" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Generators**\n", "Introduced in Python 2.2 as an optional feature and finalized in version 2.3, generators are Python's mechanism for lazy evaluation of a function that would otherwise return a space-prohibitive or computationally intensive list." ], "metadata": { "id": "_I2tPl9TLkdn" } }, { "cell_type": "code", "source": [ "import itertools\n", "\n", "def generate_primes(stop_at: Optional[int] = None) -> Iterator[int]:\n", " primes: List[int] = []\n", " for n in itertools.count(start = 2):\n", " if stop_at is not None and n > stop_at:\n", " return # raises the StopIteration exception\n", " composite: bool = False\n", " for p in primes:\n", " if not n % p:\n", " composite = True\n", " break\n", " elif p ** 2 > n:\n", " break\n", " if not composite:\n", " primes.append(n)\n", " yield n\n", "\n", "\n", "for i in generate_primes(100): # iterate over the primes between 0 and 100\n", " print(i)\n", "\n", "for i in generate_primes(): # iterate over ALL primes indefinitely\n", " print(i)" ], "metadata": { "id": "U3j0zEaaLkkY" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Generator expressions**\n", "Further information: List comprehension\n", "Introduced in Python 2.4, generator expressions are the lazy evaluation equivalent of list comprehensions. Using the prime number generator provided in the above section, we might define a lazy, but not quite infinite collection." ], "metadata": { "id": "bflHVEbtMgh8" } }, { "cell_type": "code", "source": [ "import itertools\n", "\n", "primes_under_million: Iterator[int] = (i for i in generate_primes() if i < 1000000)\n", "two_thousandth_prime: Iterator[int] = itertools.islice(primes_under_million, 1999, 2000).next()" ], "metadata": { "id": "cxiDUx41MgpT" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Dictionary and set comprehensions**\n", "While lists and generators had comprehensions/expressions, in Python versions older than 2.7 the other Python built-in collection types (dicts and sets) had to be kludged in using lists or generators:" ], "metadata": { "id": "vC3eCoeMMgyL" } }, { "cell_type": "code", "source": [ "squares = dict((n, n * n) for n in range(5))\n", "# in Python 3.5 and later the type of squares is\n", "# Dict[int, int]\n", "print(squares)\n", "# prints {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}\n", "\n", "\n", "print([n * n for n in range(5)]) # regular list comprehension\n", "# prints [0, 1, 4, 9, 16]\n", "print({n * n for n in range(5)}) # set comprehension\n", "# prints {0, 1, 4, 9, 16}\n", "print({n: n * n for n in range(5)}) # dict comprehension\n", "# prints {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}" ], "metadata": { "id": "declGG-NMg6M" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Objects**\n", "Python supports most object-oriented programming (OOP) techniques. It allows polymorphism, not only within a class hierarchy but also by duck typing. Any object can be used for any type, and it will work so long as it has the proper methods and attributes. And everything in Python is an object, including classes, functions, numbers and modules. Python also has support for metaclasses, an advanced tool for enhancing classes' functionality. Naturally, inheritance, including multiple inheritance, is supported. Python has very limited support for private variables using name mangling which is rarely used in practice as information hiding is seen by some as unpythonic, in that it suggests that the class in question contains unaesthetic or ill-planned internals. The slogan \"we're all responsible users here\" is used to describe this attitude.[30]\n", "\n", "As is true for modules, classes in Python do not put an absolute barrier between definition and user, but rather rely on the politeness of the user not to \"break into the definition.\"" ], "metadata": { "id": "i7crijG7MhBC" } }, { "cell_type": "markdown", "source": [ "# **With statement**\n", "The with statement handles resources, and allows users to work with the Context Manager protocol.[31] One function (__enter__()) is called when entering scope and another (__exit__()) when leaving. This prevents forgetting to free the resource and also handles more complicated situations such as freeing the resource when an exception occurs while it is in use. Context Managers are often used with files, database connections, test cases, etc." ], "metadata": { "id": "ktYu_ZSHMhPT" } }, { "cell_type": "markdown", "source": [ "# **Properties**\n", "Properties allow specially defined methods to be invoked on an object instance by using the same syntax as used for attribute access. An example of a class defining some properties is:" ], "metadata": { "id": "sUih9VDbNVwD" } }, { "cell_type": "code", "source": [ "class MyClass:\n", " def __init__(self):\n", " self._a: int = 0\n", "\n", " @property\n", " def a(self) -> int:\n", " return self._a\n", "\n", " @a.setter # makes the property writable\n", " def a(self, value: int) -> None:\n", " self._a = value" ], "metadata": { "id": "Puck3UVRNV2L" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "# **Descriptors**\n", "A class that defines one or more of the three special methods __get__(self, instance, owner), __set__(self, instance, value), __delete__(self, instance) can be used as a descriptor. Creating an instance of a descriptor as a class member of a second class makes the instance a property of the second class.[32]\n", "\n", "# **Class and static methods**\n", "Python allows the creation of class methods and static methods via the use of the @classmethod and @staticmethod decorators. The first argument to a class method is the class object instead of the self-reference to the instance. A static method has no special first argument. Neither the instance, nor the class object is passed to a static method.\n", "\n" ], "metadata": { "id": "uuUSe1GfNV8d" } } ] }