{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Python \n", "\n", "## Statements and Builtin Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Python has some basic expressions called statements.\n", "#### Statements are instructions written in the source code for execution, but they are not functions. \n", "\n", "There are different types of statements in the Python programming language like *Assignment* statement, *Conditional* statements, *Looping* statements etc. These all help the user to get the required output. \n", "\n", "These are the most common Python statements:\n", "\n", "#### 1. [Simple statements](https://docs.python.org/3/reference/simple_stmts.html) \n", "\n", "+ assert\n", "+ assignment (=)\n", "+ augmented_assignment (+=, -=, /=, *=)\n", "+ annotated_assignment (Python >= 3.5)\n", "+ del\n", "+ return and yield\n", "+ raise\n", "+ pass, break, continue\n", "+ import\n", "+ future\n", "+ global, nonlocal\n", "\n", "#### 2. [Compound statements](https://docs.python.org/3/reference/compound_stmts.html) \n", "\n", "+ if (stmt) + elif, else\n", "+ while (stmt) + break, continue\n", "+ for (stmt) + break, continue\n", "+ try (stmt) + except, else, finally\n", "+ with (stmt) + as\n", "+ def (def)\n", "+ class (def)\n", "+ async_with (stmt)\n", "+ async_for (stmt)\n", "+ async_func (def)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Some statements are also considered ____Keywords____.\n", "#### Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function name or any other identifier." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']\n" ] } ], "source": [ "import keyword\n", "print(keyword.kwlist)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Statements will be presented throughout the course." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python _builtin_ Functions\n", "\n", "The Python interpreter has a number of functions and types built into it that are always available. \n", "They are listed here in alphabetical order.\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "

Built-in Functions

abs()

delattr()

hash()

memoryview()

set()

all()

dict()

help()

min()

setattr()

any()

dir()

hex()

next()

slice()

ascii()

divmod()

id()

object()

sorted()

bin()

enumerate()

input()

oct()

staticmethod()

bool()

eval()

int()

open()

str()

breakpoint()

exec()

isinstance()

ord()

sum()

bytearray()

filter()

issubclass()

pow()

super()

bytes()

float()

iter()

print()

tuple()

callable()

format()

len()

property()

type()

chr()

frozenset()

list()

range()

vars()

classmethod()

getattr()

locals()

repr()

zip()

compile()

globals()

map()

reversed()

__import__()

complex()

hasattr()

max()

round()

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The [Type Creation / Conversion](https://www.tutorialspoint.com/data-type-conversion-in-python) builtin functions will be discussed when introducing Python Datatypes.\n", "\n", "+ _int_\n", "+ _float_\n", "+ _complex_\n", "+ _list_\n", "+ _str_\n", "+ _dict_\n", "+ _bool_\n", "+ _tuple_\n", "+ _set_ \n", "+ _chr_\n", "+ _ord_ \n", "+ _ord_\n", "+ _chr_\n", "+ _hex_\n", "+ _bin_\n", "+ _oct_ \n", "+ _range_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The [Functional programming](https://docs.python.org/3/howto/functional.html) builtins will be discussed when introducing Functional Programming.\n", "\n", "+ _filter_\n", "+ _map_\n", "+ _zip_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The [Class](https://docs.python.org/3/tutorial/classes.html) related builtins will be discussed when introducing Classes.\n", "\n", "+ _getattr_\n", "+ _setattr_\n", "+ _delattr_ \n", "+ _hasattr_\n", "+ _isinstance_ \n", "+ _issubclass_\n", "+ _super_ \n", "+ _classmethod_\n", "+ _staticmethod_\n", "+ _callable_" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__open__\" will be discussed when introducing Files and Data Persistence" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### In this notebook we will present the remaining builtin functions, with the most commonly used first:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1. \"__print__\" and \"__repr__\" \n", "\n", "__print__ accesses the __ __str__ __ methods of an object \n", "__repr__ accesses the __ __rep__ __ method of the object\n", "\n", "str() and repr() both are used to get a string representation of object. \n", "str() is used for creating output for end user while repr() is mainly used for debugging and development. \n", "repr’s goal is to be unambiguous and str’s is to be readable. \n", "For example, if we suspect a float has a small rounding error, repr will show us while str may not. \n", "\n", "Implement __repr__ for any class you implement. Implement __str__ if you think it would be useful to have a string version which errs on the side of readability." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "my special string\n" ] } ], "source": [ "print(\"my special string\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"'my special string'\"" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "repr(\"my special string\")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 8]\n" ] } ], "source": [ "list1 = [1,2,3,8]\n", "print(list1)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'[1, 2, 3, 8]'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "repr(list1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Print formatting" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "name = ['Sheldon', 'Penny', 'Leonard']\n", "age = [30, 25, 35]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1. Using % Operator" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The character Sheldon is 30 years old\n", "The character Penny is 25 years old\n", "The character Leonard is 35 years old\n" ] } ], "source": [ "for i, j in zip(name, age):\n", " print('The character %s is %d years old'%(i,j))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "2. Using string. format" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The character Sheldon is 30 years old\n", "The character Penny is 25 years old\n", "The character Leonard is 35 years old\n" ] } ], "source": [ "for i, j in zip(name, age):\n", " print('The character {1} is {0} years old'.format(j,i))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "3. Using f-strings" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The character Sheldon is 30 years old\n", "The character Penny is 25 years old\n", "The character Leonard is 35 years old\n" ] } ], "source": [ "for i, j in zip(name, age):\n", " print(f'The character {i} is {j} years old')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Other uses for f-strings: operations" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "the car will travel for 60 Km\n" ] } ], "source": [ "speed = 30\n", "time = 2\n", "print(f'the car will travel for {speed * time} Km')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Date formatting" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2021-06-21 14:19:56.705976\n", "2021-06-21\n", "2021-06-21\n" ] } ], "source": [ "from datetime import datetime\n", "now = datetime.now()\n", "print(now)\n", "print(now.strftime(\"%Y-%m-%d\"))\n", "print(f\"{now:%Y-%m-%d}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Adding separators:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1234567890\n", "1,234,567,890\n", "1_234_567_890\n", "1 234 567 890\n" ] } ], "source": [ "num = 1234567890\n", "print(f\"{num}\")\n", "print(f\"{num:,}\")\n", "print(f\"{num:_}\")\n", "print(f\"{num:,}\".replace(',',' '))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Justifying and centering" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\n", " Hello\n", " Hello \n", "***Hello***\n" ] } ], "source": [ "msg = 'Hello'\n", "print(f'{msg}')\n", "print(f'{msg:>10}')\n", "print(f'{msg:^11}')\n", "print(f'{msg:*^11}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Using if-else Conditional:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "T\n" ] } ], "source": [ "x = 'T'\n", "y = 'F'\n", "print(f'{x if 10 > 5 else y}')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 2. \"__type__\"" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(\"my special string\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3. \"__len__\"" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len([1, 9, 2, 7, 3, 8])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4. \"__help__\"" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on _Helper in module _sitebuiltins object:\n", "\n", "class _Helper(builtins.object)\n", " | Define the builtin 'help'.\n", " | \n", " | This is a wrapper around pydoc.help that provides a helpful message\n", " | when 'help' is typed at the Python interactive prompt.\n", " | \n", " | Calling help() at the Python prompt starts an interactive help session.\n", " | Calling help(thing) prints help for the python object 'thing'.\n", " | \n", " | Methods defined here:\n", " | \n", " | __call__(self, *args, **kwds)\n", " | Call self as a function.\n", " | \n", " | __repr__(self)\n", " | Return repr(self).\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors defined here:\n", " | \n", " | __dict__\n", " | dictionary for instance variables (if defined)\n", " | \n", " | __weakref__\n", " | list of weak references to the object (if defined)\n", "\n" ] } ], "source": [ "help(help)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5. \"__dir__\"" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__abs__',\n", " '__add__',\n", " '__and__',\n", " '__bool__',\n", " '__ceil__',\n", " '__class__',\n", " '__delattr__',\n", " '__dir__',\n", " '__divmod__',\n", " '__doc__',\n", " '__eq__',\n", " '__float__',\n", " '__floor__',\n", " '__floordiv__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__index__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__int__',\n", " '__invert__',\n", " '__le__',\n", " '__lshift__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__neg__',\n", " '__new__',\n", " '__or__',\n", " '__pos__',\n", " '__pow__',\n", " '__radd__',\n", " '__rand__',\n", " '__rdivmod__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rfloordiv__',\n", " '__rlshift__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__ror__',\n", " '__round__',\n", " '__rpow__',\n", " '__rrshift__',\n", " '__rshift__',\n", " '__rsub__',\n", " '__rtruediv__',\n", " '__rxor__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__sub__',\n", " '__subclasshook__',\n", " '__truediv__',\n", " '__trunc__',\n", " '__xor__',\n", " 'as_integer_ratio',\n", " 'bit_length',\n", " 'conjugate',\n", " 'denominator',\n", " 'from_bytes',\n", " 'imag',\n", " 'numerator',\n", " 'real',\n", " 'to_bytes']" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_integer = 6\n", "dir(my_integer)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 6. \"___import___\" \n", "This function is invoked by the import statement." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "import numpy\n", "# is equivalent to\n", "numpy = __import__('numpy', globals(), locals(), [], 0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 7. \"__abs__\" and \"__round__\"" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "abs(-5)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "round(7.45)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 8. \"__max__\" and \"__min__\"" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "8" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max([1,5,8,4])" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "min([1,5,8,4])" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'He'" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "min([\"I\", \"You\", \"He\", \"She\", \"It\"])" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'<' not supported between instances of 'str' and 'int'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmin\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;36m8\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\"we\"\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m## error\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: '<' not supported between instances of 'str' and 'int'" ] } ], "source": [ "min([1,5,8,\"we\"]) ## error" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 9. \"__sum__\"" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "18" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum([1,5,8,4])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 10. \"__pow__\" \n", "+ Return base to the power exp; if mod is present, return base to the power exp, modulo mod" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 11. \"__sorted__\" and \"__reversed__\"" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 5, 8]" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted([1,5,8,4])" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[4, 8, 5, 1]" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(reversed([1,5,8,4]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 12. \"__globals__\" , \"__locals__\" and \"__vars__\" \n", "+ *globals* return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called). \n", "+ *locals* return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks. Note that at the module level, locals() and globals() are the same dictionary.\n", "+ *vars* Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'__name__': '__main__',\n", " '__doc__': 'Automatically created module for IPython interactive environment',\n", " '__package__': None,\n", " '__loader__': None,\n", " '__spec__': None,\n", " '__builtin__': ,\n", " '__builtins__': ,\n", " '_ih': ['',\n", " 'import keyword\\nprint(keyword.kwlist)',\n", " 'print(\"my special string\")',\n", " 'repr(\"my special string\")',\n", " 'list1 = [1,2,3,8]\\nprint(list1)',\n", " 'repr(list1)',\n", " \"name = ['Sheldon', 'Penny', 'Leonard']\\nage = [30, 25, 35]\",\n", " \"for i, j in zip(name, age):\\n print('The character %s is %d years old'%(i,j))\",\n", " \"for i, j in zip(name, age):\\n print('The character {1} is {0} years old'.format(j,i))\",\n", " \"for i, j in zip(name, age):\\n print(f'The character {i} is {j} years old')\",\n", " \"speed = 30\\ntime = 2\\nprint(f'the car will travel for {speed * time} Km')\",\n", " 'from datetime import datetime\\nnow = datetime.now()\\nprint(now)\\nprint(now.strftime(\"%Y-%m-%d\"))\\nprint(f\"{now:%Y-%m-%d}\")',\n", " 'num = 1234567890\\nprint(f\"{num}\")\\nprint(f\"{num:,}\")\\nprint(f\"{num:_}\")\\nprint(f\"{num:,}\".replace(\\',\\',\\' \\'))',\n", " \"msg = 'Hello'\\nprint(f'{msg}')\\nprint(f'{msg:>10}')\\nprint(f'{msg:^11}')\\nprint(f'{msg:*^11}')\",\n", " \"x = 'T'\\ny = 'F'\\nprint(f'{x if 10 > 5 else y}')\",\n", " 'type(\"my special string\")',\n", " 'len([1, 9, 2, 7, 3, 8])',\n", " 'help(help)',\n", " 'my_integer = 6\\ndir(my_integer)',\n", " \"import numpy\\n# is equivalent to\\nnumpy = __import__('numpy', globals(), locals(), [], 0)\",\n", " 'abs(-5)',\n", " 'round(7.45)',\n", " 'max([1,5,8,4])',\n", " 'min([1,5,8,4])',\n", " 'min([\"I\", \"You\", \"He\", \"She\", \"It\"])',\n", " 'min([1,5,8,\"we\"]) ## error',\n", " 'sum([1,5,8,4])',\n", " 'sorted([1,5,8,4])',\n", " 'list(reversed([1,5,8,4]))',\n", " 'locals()'],\n", " '_oh': {3: \"'my special string'\",\n", " 5: '[1, 2, 3, 8]',\n", " 15: str,\n", " 16: 6,\n", " 18: ['__abs__',\n", " '__add__',\n", " '__and__',\n", " '__bool__',\n", " '__ceil__',\n", " '__class__',\n", " '__delattr__',\n", " '__dir__',\n", " '__divmod__',\n", " '__doc__',\n", " '__eq__',\n", " '__float__',\n", " '__floor__',\n", " '__floordiv__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__index__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__int__',\n", " '__invert__',\n", " '__le__',\n", " '__lshift__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__neg__',\n", " '__new__',\n", " '__or__',\n", " '__pos__',\n", " '__pow__',\n", " '__radd__',\n", " '__rand__',\n", " '__rdivmod__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rfloordiv__',\n", " '__rlshift__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__ror__',\n", " '__round__',\n", " '__rpow__',\n", " '__rrshift__',\n", " '__rshift__',\n", " '__rsub__',\n", " '__rtruediv__',\n", " '__rxor__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__sub__',\n", " '__subclasshook__',\n", " '__truediv__',\n", " '__trunc__',\n", " '__xor__',\n", " 'as_integer_ratio',\n", " 'bit_length',\n", " 'conjugate',\n", " 'denominator',\n", " 'from_bytes',\n", " 'imag',\n", " 'numerator',\n", " 'real',\n", " 'to_bytes'],\n", " 20: 5,\n", " 21: 7,\n", " 22: 8,\n", " 23: 1,\n", " 24: 'He',\n", " 26: 18,\n", " 27: [1, 4, 5, 8],\n", " 28: [4, 8, 5, 1]},\n", " '_dh': ['/home/rsouza/Documents/Repos/Python_Course/Notebooks'],\n", " 'In': ['',\n", " 'import keyword\\nprint(keyword.kwlist)',\n", " 'print(\"my special string\")',\n", " 'repr(\"my special string\")',\n", " 'list1 = [1,2,3,8]\\nprint(list1)',\n", " 'repr(list1)',\n", " \"name = ['Sheldon', 'Penny', 'Leonard']\\nage = [30, 25, 35]\",\n", " \"for i, j in zip(name, age):\\n print('The character %s is %d years old'%(i,j))\",\n", " \"for i, j in zip(name, age):\\n print('The character {1} is {0} years old'.format(j,i))\",\n", " \"for i, j in zip(name, age):\\n print(f'The character {i} is {j} years old')\",\n", " \"speed = 30\\ntime = 2\\nprint(f'the car will travel for {speed * time} Km')\",\n", " 'from datetime import datetime\\nnow = datetime.now()\\nprint(now)\\nprint(now.strftime(\"%Y-%m-%d\"))\\nprint(f\"{now:%Y-%m-%d}\")',\n", " 'num = 1234567890\\nprint(f\"{num}\")\\nprint(f\"{num:,}\")\\nprint(f\"{num:_}\")\\nprint(f\"{num:,}\".replace(\\',\\',\\' \\'))',\n", " \"msg = 'Hello'\\nprint(f'{msg}')\\nprint(f'{msg:>10}')\\nprint(f'{msg:^11}')\\nprint(f'{msg:*^11}')\",\n", " \"x = 'T'\\ny = 'F'\\nprint(f'{x if 10 > 5 else y}')\",\n", " 'type(\"my special string\")',\n", " 'len([1, 9, 2, 7, 3, 8])',\n", " 'help(help)',\n", " 'my_integer = 6\\ndir(my_integer)',\n", " \"import numpy\\n# is equivalent to\\nnumpy = __import__('numpy', globals(), locals(), [], 0)\",\n", " 'abs(-5)',\n", " 'round(7.45)',\n", " 'max([1,5,8,4])',\n", " 'min([1,5,8,4])',\n", " 'min([\"I\", \"You\", \"He\", \"She\", \"It\"])',\n", " 'min([1,5,8,\"we\"]) ## error',\n", " 'sum([1,5,8,4])',\n", " 'sorted([1,5,8,4])',\n", " 'list(reversed([1,5,8,4]))',\n", " 'locals()'],\n", " 'Out': {3: \"'my special string'\",\n", " 5: '[1, 2, 3, 8]',\n", " 15: str,\n", " 16: 6,\n", " 18: ['__abs__',\n", " '__add__',\n", " '__and__',\n", " '__bool__',\n", " '__ceil__',\n", " '__class__',\n", " '__delattr__',\n", " '__dir__',\n", " '__divmod__',\n", " '__doc__',\n", " '__eq__',\n", " '__float__',\n", " '__floor__',\n", " '__floordiv__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__index__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__int__',\n", " '__invert__',\n", " '__le__',\n", " '__lshift__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__neg__',\n", " '__new__',\n", " '__or__',\n", " '__pos__',\n", " '__pow__',\n", " '__radd__',\n", " '__rand__',\n", " '__rdivmod__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rfloordiv__',\n", " '__rlshift__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__ror__',\n", " '__round__',\n", " '__rpow__',\n", " '__rrshift__',\n", " '__rshift__',\n", " '__rsub__',\n", " '__rtruediv__',\n", " '__rxor__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__sub__',\n", " '__subclasshook__',\n", " '__truediv__',\n", " '__trunc__',\n", " '__xor__',\n", " 'as_integer_ratio',\n", " 'bit_length',\n", " 'conjugate',\n", " 'denominator',\n", " 'from_bytes',\n", " 'imag',\n", " 'numerator',\n", " 'real',\n", " 'to_bytes'],\n", " 20: 5,\n", " 21: 7,\n", " 22: 8,\n", " 23: 1,\n", " 24: 'He',\n", " 26: 18,\n", " 27: [1, 4, 5, 8],\n", " 28: [4, 8, 5, 1]},\n", " 'get_ipython': >,\n", " 'exit': ,\n", " 'quit': ,\n", " '_': [4, 8, 5, 1],\n", " '__': [1, 4, 5, 8],\n", " '___': 18,\n", " '_i': 'list(reversed([1,5,8,4]))',\n", " '_ii': 'sorted([1,5,8,4])',\n", " '_iii': 'sum([1,5,8,4])',\n", " '_i1': 'import keyword\\nprint(keyword.kwlist)',\n", " 'keyword': ,\n", " '_i2': 'print(\"my special string\")',\n", " '_i3': 'repr(\"my special string\")',\n", " '_3': \"'my special string'\",\n", " '_i4': 'list1 = [1,2,3,8]\\nprint(list1)',\n", " 'list1': [1, 2, 3, 8],\n", " '_i5': 'repr(list1)',\n", " '_5': '[1, 2, 3, 8]',\n", " '_i6': \"name = ['Sheldon', 'Penny', 'Leonard']\\nage = [30, 25, 35]\",\n", " 'name': ['Sheldon', 'Penny', 'Leonard'],\n", " 'age': [30, 25, 35],\n", " '_i7': \"for i, j in zip(name, age):\\n print('The character %s is %d years old'%(i,j))\",\n", " 'i': 'Leonard',\n", " 'j': 35,\n", " '_i8': \"for i, j in zip(name, age):\\n print('The character {1} is {0} years old'.format(j,i))\",\n", " '_i9': \"for i, j in zip(name, age):\\n print(f'The character {i} is {j} years old')\",\n", " '_i10': \"speed = 30\\ntime = 2\\nprint(f'the car will travel for {speed * time} Km')\",\n", " 'speed': 30,\n", " 'time': 2,\n", " '_i11': 'from datetime import datetime\\nnow = datetime.now()\\nprint(now)\\nprint(now.strftime(\"%Y-%m-%d\"))\\nprint(f\"{now:%Y-%m-%d}\")',\n", " 'datetime': datetime.datetime,\n", " 'now': datetime.datetime(2021, 6, 21, 14, 19, 56, 705976),\n", " '_i12': 'num = 1234567890\\nprint(f\"{num}\")\\nprint(f\"{num:,}\")\\nprint(f\"{num:_}\")\\nprint(f\"{num:,}\".replace(\\',\\',\\' \\'))',\n", " 'num': 1234567890,\n", " '_i13': \"msg = 'Hello'\\nprint(f'{msg}')\\nprint(f'{msg:>10}')\\nprint(f'{msg:^11}')\\nprint(f'{msg:*^11}')\",\n", " 'msg': 'Hello',\n", " '_i14': \"x = 'T'\\ny = 'F'\\nprint(f'{x if 10 > 5 else y}')\",\n", " 'x': 'T',\n", " 'y': 'F',\n", " '_i15': 'type(\"my special string\")',\n", " '_15': str,\n", " '_i16': 'len([1, 9, 2, 7, 3, 8])',\n", " '_16': 6,\n", " '_i17': 'help(help)',\n", " '_i18': 'my_integer = 6\\ndir(my_integer)',\n", " 'my_integer': 6,\n", " '_18': ['__abs__',\n", " '__add__',\n", " '__and__',\n", " '__bool__',\n", " '__ceil__',\n", " '__class__',\n", " '__delattr__',\n", " '__dir__',\n", " '__divmod__',\n", " '__doc__',\n", " '__eq__',\n", " '__float__',\n", " '__floor__',\n", " '__floordiv__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__index__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__int__',\n", " '__invert__',\n", " '__le__',\n", " '__lshift__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__neg__',\n", " '__new__',\n", " '__or__',\n", " '__pos__',\n", " '__pow__',\n", " '__radd__',\n", " '__rand__',\n", " '__rdivmod__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rfloordiv__',\n", " '__rlshift__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__ror__',\n", " '__round__',\n", " '__rpow__',\n", " '__rrshift__',\n", " '__rshift__',\n", " '__rsub__',\n", " '__rtruediv__',\n", " '__rxor__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__sub__',\n", " '__subclasshook__',\n", " '__truediv__',\n", " '__trunc__',\n", " '__xor__',\n", " 'as_integer_ratio',\n", " 'bit_length',\n", " 'conjugate',\n", " 'denominator',\n", " 'from_bytes',\n", " 'imag',\n", " 'numerator',\n", " 'real',\n", " 'to_bytes'],\n", " '_i19': \"import numpy\\n# is equivalent to\\nnumpy = __import__('numpy', globals(), locals(), [], 0)\",\n", " 'numpy': ,\n", " '_i20': 'abs(-5)',\n", " '_20': 5,\n", " '_i21': 'round(7.45)',\n", " '_21': 7,\n", " '_i22': 'max([1,5,8,4])',\n", " '_22': 8,\n", " '_i23': 'min([1,5,8,4])',\n", " '_23': 1,\n", " '_i24': 'min([\"I\", \"You\", \"He\", \"She\", \"It\"])',\n", " '_24': 'He',\n", " '_i25': 'min([1,5,8,\"we\"]) ## error',\n", " '_i26': 'sum([1,5,8,4])',\n", " '_26': 18,\n", " '_i27': 'sorted([1,5,8,4])',\n", " '_27': [1, 4, 5, 8],\n", " '_i28': 'list(reversed([1,5,8,4]))',\n", " '_28': [4, 8, 5, 1],\n", " '_i29': 'locals()'}" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "locals()" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'__name__': '__main__',\n", " '__doc__': 'Automatically created module for IPython interactive environment',\n", " '__package__': None,\n", " '__loader__': None,\n", " '__spec__': None,\n", " '__builtin__': ,\n", " '__builtins__': ,\n", " '_ih': ['',\n", " 'import keyword\\nprint(keyword.kwlist)',\n", " 'print(\"my special string\")',\n", " 'repr(\"my special string\")',\n", " 'list1 = [1,2,3,8]\\nprint(list1)',\n", " 'repr(list1)',\n", " \"name = ['Sheldon', 'Penny', 'Leonard']\\nage = [30, 25, 35]\",\n", " \"for i, j in zip(name, age):\\n print('The character %s is %d years old'%(i,j))\",\n", " \"for i, j in zip(name, age):\\n print('The character {1} is {0} years old'.format(j,i))\",\n", " \"for i, j in zip(name, age):\\n print(f'The character {i} is {j} years old')\",\n", " \"speed = 30\\ntime = 2\\nprint(f'the car will travel for {speed * time} Km')\",\n", " 'from datetime import datetime\\nnow = datetime.now()\\nprint(now)\\nprint(now.strftime(\"%Y-%m-%d\"))\\nprint(f\"{now:%Y-%m-%d}\")',\n", " 'num = 1234567890\\nprint(f\"{num}\")\\nprint(f\"{num:,}\")\\nprint(f\"{num:_}\")\\nprint(f\"{num:,}\".replace(\\',\\',\\' \\'))',\n", " \"msg = 'Hello'\\nprint(f'{msg}')\\nprint(f'{msg:>10}')\\nprint(f'{msg:^11}')\\nprint(f'{msg:*^11}')\",\n", " \"x = 'T'\\ny = 'F'\\nprint(f'{x if 10 > 5 else y}')\",\n", " 'type(\"my special string\")',\n", " 'len([1, 9, 2, 7, 3, 8])',\n", " 'help(help)',\n", " 'my_integer = 6\\ndir(my_integer)',\n", " \"import numpy\\n# is equivalent to\\nnumpy = __import__('numpy', globals(), locals(), [], 0)\",\n", " 'abs(-5)',\n", " 'round(7.45)',\n", " 'max([1,5,8,4])',\n", " 'min([1,5,8,4])',\n", " 'min([\"I\", \"You\", \"He\", \"She\", \"It\"])',\n", " 'min([1,5,8,\"we\"]) ## error',\n", " 'sum([1,5,8,4])',\n", " 'sorted([1,5,8,4])',\n", " 'list(reversed([1,5,8,4]))',\n", " 'locals()',\n", " 'globals()'],\n", " '_oh': {3: \"'my special string'\",\n", " 5: '[1, 2, 3, 8]',\n", " 15: str,\n", " 16: 6,\n", " 18: ['__abs__',\n", " '__add__',\n", " '__and__',\n", " '__bool__',\n", " '__ceil__',\n", " '__class__',\n", " '__delattr__',\n", " '__dir__',\n", " '__divmod__',\n", " '__doc__',\n", " '__eq__',\n", " '__float__',\n", " '__floor__',\n", " '__floordiv__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__index__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__int__',\n", " '__invert__',\n", " '__le__',\n", " '__lshift__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__neg__',\n", " '__new__',\n", " '__or__',\n", " '__pos__',\n", " '__pow__',\n", " '__radd__',\n", " '__rand__',\n", " '__rdivmod__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rfloordiv__',\n", " '__rlshift__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__ror__',\n", " '__round__',\n", " '__rpow__',\n", " '__rrshift__',\n", " '__rshift__',\n", " '__rsub__',\n", " '__rtruediv__',\n", " '__rxor__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__sub__',\n", " '__subclasshook__',\n", " '__truediv__',\n", " '__trunc__',\n", " '__xor__',\n", " 'as_integer_ratio',\n", " 'bit_length',\n", " 'conjugate',\n", " 'denominator',\n", " 'from_bytes',\n", " 'imag',\n", " 'numerator',\n", " 'real',\n", " 'to_bytes'],\n", " 20: 5,\n", " 21: 7,\n", " 22: 8,\n", " 23: 1,\n", " 24: 'He',\n", " 26: 18,\n", " 27: [1, 4, 5, 8],\n", " 28: [4, 8, 5, 1],\n", " 29: {...}},\n", " '_dh': ['/home/rsouza/Documents/Repos/Python_Course/Notebooks'],\n", " 'In': ['',\n", " 'import keyword\\nprint(keyword.kwlist)',\n", " 'print(\"my special string\")',\n", " 'repr(\"my special string\")',\n", " 'list1 = [1,2,3,8]\\nprint(list1)',\n", " 'repr(list1)',\n", " \"name = ['Sheldon', 'Penny', 'Leonard']\\nage = [30, 25, 35]\",\n", " \"for i, j in zip(name, age):\\n print('The character %s is %d years old'%(i,j))\",\n", " \"for i, j in zip(name, age):\\n print('The character {1} is {0} years old'.format(j,i))\",\n", " \"for i, j in zip(name, age):\\n print(f'The character {i} is {j} years old')\",\n", " \"speed = 30\\ntime = 2\\nprint(f'the car will travel for {speed * time} Km')\",\n", " 'from datetime import datetime\\nnow = datetime.now()\\nprint(now)\\nprint(now.strftime(\"%Y-%m-%d\"))\\nprint(f\"{now:%Y-%m-%d}\")',\n", " 'num = 1234567890\\nprint(f\"{num}\")\\nprint(f\"{num:,}\")\\nprint(f\"{num:_}\")\\nprint(f\"{num:,}\".replace(\\',\\',\\' \\'))',\n", " \"msg = 'Hello'\\nprint(f'{msg}')\\nprint(f'{msg:>10}')\\nprint(f'{msg:^11}')\\nprint(f'{msg:*^11}')\",\n", " \"x = 'T'\\ny = 'F'\\nprint(f'{x if 10 > 5 else y}')\",\n", " 'type(\"my special string\")',\n", " 'len([1, 9, 2, 7, 3, 8])',\n", " 'help(help)',\n", " 'my_integer = 6\\ndir(my_integer)',\n", " \"import numpy\\n# is equivalent to\\nnumpy = __import__('numpy', globals(), locals(), [], 0)\",\n", " 'abs(-5)',\n", " 'round(7.45)',\n", " 'max([1,5,8,4])',\n", " 'min([1,5,8,4])',\n", " 'min([\"I\", \"You\", \"He\", \"She\", \"It\"])',\n", " 'min([1,5,8,\"we\"]) ## error',\n", " 'sum([1,5,8,4])',\n", " 'sorted([1,5,8,4])',\n", " 'list(reversed([1,5,8,4]))',\n", " 'locals()',\n", " 'globals()'],\n", " 'Out': {3: \"'my special string'\",\n", " 5: '[1, 2, 3, 8]',\n", " 15: str,\n", " 16: 6,\n", " 18: ['__abs__',\n", " '__add__',\n", " '__and__',\n", " '__bool__',\n", " '__ceil__',\n", " '__class__',\n", " '__delattr__',\n", " '__dir__',\n", " '__divmod__',\n", " '__doc__',\n", " '__eq__',\n", " '__float__',\n", " '__floor__',\n", " '__floordiv__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__index__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__int__',\n", " '__invert__',\n", " '__le__',\n", " '__lshift__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__neg__',\n", " '__new__',\n", " '__or__',\n", " '__pos__',\n", " '__pow__',\n", " '__radd__',\n", " '__rand__',\n", " '__rdivmod__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rfloordiv__',\n", " '__rlshift__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__ror__',\n", " '__round__',\n", " '__rpow__',\n", " '__rrshift__',\n", " '__rshift__',\n", " '__rsub__',\n", " '__rtruediv__',\n", " '__rxor__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__sub__',\n", " '__subclasshook__',\n", " '__truediv__',\n", " '__trunc__',\n", " '__xor__',\n", " 'as_integer_ratio',\n", " 'bit_length',\n", " 'conjugate',\n", " 'denominator',\n", " 'from_bytes',\n", " 'imag',\n", " 'numerator',\n", " 'real',\n", " 'to_bytes'],\n", " 20: 5,\n", " 21: 7,\n", " 22: 8,\n", " 23: 1,\n", " 24: 'He',\n", " 26: 18,\n", " 27: [1, 4, 5, 8],\n", " 28: [4, 8, 5, 1],\n", " 29: {...}},\n", " 'get_ipython': >,\n", " 'exit': ,\n", " 'quit': ,\n", " '_': {...},\n", " '__': [4, 8, 5, 1],\n", " '___': [1, 4, 5, 8],\n", " '_i': 'locals()',\n", " '_ii': 'list(reversed([1,5,8,4]))',\n", " '_iii': 'sorted([1,5,8,4])',\n", " '_i1': 'import keyword\\nprint(keyword.kwlist)',\n", " 'keyword': ,\n", " '_i2': 'print(\"my special string\")',\n", " '_i3': 'repr(\"my special string\")',\n", " '_3': \"'my special string'\",\n", " '_i4': 'list1 = [1,2,3,8]\\nprint(list1)',\n", " 'list1': [1, 2, 3, 8],\n", " '_i5': 'repr(list1)',\n", " '_5': '[1, 2, 3, 8]',\n", " '_i6': \"name = ['Sheldon', 'Penny', 'Leonard']\\nage = [30, 25, 35]\",\n", " 'name': ['Sheldon', 'Penny', 'Leonard'],\n", " 'age': [30, 25, 35],\n", " '_i7': \"for i, j in zip(name, age):\\n print('The character %s is %d years old'%(i,j))\",\n", " 'i': 'Leonard',\n", " 'j': 35,\n", " '_i8': \"for i, j in zip(name, age):\\n print('The character {1} is {0} years old'.format(j,i))\",\n", " '_i9': \"for i, j in zip(name, age):\\n print(f'The character {i} is {j} years old')\",\n", " '_i10': \"speed = 30\\ntime = 2\\nprint(f'the car will travel for {speed * time} Km')\",\n", " 'speed': 30,\n", " 'time': 2,\n", " '_i11': 'from datetime import datetime\\nnow = datetime.now()\\nprint(now)\\nprint(now.strftime(\"%Y-%m-%d\"))\\nprint(f\"{now:%Y-%m-%d}\")',\n", " 'datetime': datetime.datetime,\n", " 'now': datetime.datetime(2021, 6, 21, 14, 19, 56, 705976),\n", " '_i12': 'num = 1234567890\\nprint(f\"{num}\")\\nprint(f\"{num:,}\")\\nprint(f\"{num:_}\")\\nprint(f\"{num:,}\".replace(\\',\\',\\' \\'))',\n", " 'num': 1234567890,\n", " '_i13': \"msg = 'Hello'\\nprint(f'{msg}')\\nprint(f'{msg:>10}')\\nprint(f'{msg:^11}')\\nprint(f'{msg:*^11}')\",\n", " 'msg': 'Hello',\n", " '_i14': \"x = 'T'\\ny = 'F'\\nprint(f'{x if 10 > 5 else y}')\",\n", " 'x': 'T',\n", " 'y': 'F',\n", " '_i15': 'type(\"my special string\")',\n", " '_15': str,\n", " '_i16': 'len([1, 9, 2, 7, 3, 8])',\n", " '_16': 6,\n", " '_i17': 'help(help)',\n", " '_i18': 'my_integer = 6\\ndir(my_integer)',\n", " 'my_integer': 6,\n", " '_18': ['__abs__',\n", " '__add__',\n", " '__and__',\n", " '__bool__',\n", " '__ceil__',\n", " '__class__',\n", " '__delattr__',\n", " '__dir__',\n", " '__divmod__',\n", " '__doc__',\n", " '__eq__',\n", " '__float__',\n", " '__floor__',\n", " '__floordiv__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getnewargs__',\n", " '__gt__',\n", " '__hash__',\n", " '__index__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__int__',\n", " '__invert__',\n", " '__le__',\n", " '__lshift__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__neg__',\n", " '__new__',\n", " '__or__',\n", " '__pos__',\n", " '__pow__',\n", " '__radd__',\n", " '__rand__',\n", " '__rdivmod__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rfloordiv__',\n", " '__rlshift__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__ror__',\n", " '__round__',\n", " '__rpow__',\n", " '__rrshift__',\n", " '__rshift__',\n", " '__rsub__',\n", " '__rtruediv__',\n", " '__rxor__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__sub__',\n", " '__subclasshook__',\n", " '__truediv__',\n", " '__trunc__',\n", " '__xor__',\n", " 'as_integer_ratio',\n", " 'bit_length',\n", " 'conjugate',\n", " 'denominator',\n", " 'from_bytes',\n", " 'imag',\n", " 'numerator',\n", " 'real',\n", " 'to_bytes'],\n", " '_i19': \"import numpy\\n# is equivalent to\\nnumpy = __import__('numpy', globals(), locals(), [], 0)\",\n", " 'numpy': ,\n", " '_i20': 'abs(-5)',\n", " '_20': 5,\n", " '_i21': 'round(7.45)',\n", " '_21': 7,\n", " '_i22': 'max([1,5,8,4])',\n", " '_22': 8,\n", " '_i23': 'min([1,5,8,4])',\n", " '_23': 1,\n", " '_i24': 'min([\"I\", \"You\", \"He\", \"She\", \"It\"])',\n", " '_24': 'He',\n", " '_i25': 'min([1,5,8,\"we\"]) ## error',\n", " '_i26': 'sum([1,5,8,4])',\n", " '_26': 18,\n", " '_i27': 'sorted([1,5,8,4])',\n", " '_27': [1, 4, 5, 8],\n", " '_i28': 'list(reversed([1,5,8,4]))',\n", " '_28': [4, 8, 5, 1],\n", " '_i29': 'locals()',\n", " '_29': {...},\n", " '_i30': 'globals()'}" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "globals()" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'__name__': 'string',\n", " '__doc__': 'A collection of string constants.\\n\\nPublic module variables:\\n\\nwhitespace -- a string containing all ASCII whitespace\\nascii_lowercase -- a string containing all ASCII lowercase letters\\nascii_uppercase -- a string containing all ASCII uppercase letters\\nascii_letters -- a string containing all ASCII letters\\ndigits -- a string containing all ASCII decimal digits\\nhexdigits -- a string containing all ASCII hexadecimal digits\\noctdigits -- a string containing all ASCII octal digits\\npunctuation -- a string containing all ASCII punctuation characters\\nprintable -- a string containing all ASCII characters considered printable\\n\\n',\n", " '__package__': '',\n", " '__loader__': <_frozen_importlib_external.SourceFileLoader at 0x7fd82390fee0>,\n", " '__spec__': ModuleSpec(name='string', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fd82390fee0>, origin='/usr/lib/python3.8/string.py'),\n", " '__file__': '/usr/lib/python3.8/string.py',\n", " '__cached__': '/usr/lib/python3.8/__pycache__/string.cpython-38.pyc',\n", " '__builtins__': {'__name__': 'builtins',\n", " '__doc__': \"Built-in functions, exceptions, and other objects.\\n\\nNoteworthy: None is the `nil' object; Ellipsis represents `...' in slices.\",\n", " '__package__': '',\n", " '__loader__': _frozen_importlib.BuiltinImporter,\n", " '__spec__': ModuleSpec(name='builtins', loader=),\n", " '__build_class__': ,\n", " '__import__': ,\n", " 'abs': ,\n", " 'all': ,\n", " 'any': ,\n", " 'ascii': ,\n", " 'bin': ,\n", " 'breakpoint': ,\n", " 'callable': ,\n", " 'chr': ,\n", " 'compile': ,\n", " 'delattr': ,\n", " 'dir': ,\n", " 'divmod': ,\n", " 'eval': ,\n", " 'exec': ,\n", " 'format': ,\n", " 'getattr': ,\n", " 'globals': ,\n", " 'hasattr': ,\n", " 'hash': ,\n", " 'hex': ,\n", " 'id': ,\n", " 'input': >,\n", " 'isinstance': ,\n", " 'issubclass': ,\n", " 'iter': ,\n", " 'len': ,\n", " 'locals': ,\n", " 'max': ,\n", " 'min': ,\n", " 'next': ,\n", " 'oct': ,\n", " 'ord': ,\n", " 'pow': ,\n", " 'print': ,\n", " 'repr': ,\n", " 'round': ,\n", " 'setattr': ,\n", " 'sorted': ,\n", " 'sum': ,\n", " 'vars': ,\n", " 'None': None,\n", " 'Ellipsis': Ellipsis,\n", " 'NotImplemented': NotImplemented,\n", " 'False': False,\n", " 'True': True,\n", " 'bool': bool,\n", " 'memoryview': memoryview,\n", " 'bytearray': bytearray,\n", " 'bytes': bytes,\n", " 'classmethod': classmethod,\n", " 'complex': complex,\n", " 'dict': dict,\n", " 'enumerate': enumerate,\n", " 'filter': filter,\n", " 'float': float,\n", " 'frozenset': frozenset,\n", " 'property': property,\n", " 'int': int,\n", " 'list': list,\n", " 'map': map,\n", " 'object': object,\n", " 'range': range,\n", " 'reversed': reversed,\n", " 'set': set,\n", " 'slice': slice,\n", " 'staticmethod': staticmethod,\n", " 'str': str,\n", " 'super': super,\n", " 'tuple': tuple,\n", " 'type': type,\n", " 'zip': zip,\n", " '__debug__': True,\n", " 'BaseException': BaseException,\n", " 'Exception': Exception,\n", " 'TypeError': TypeError,\n", " 'StopAsyncIteration': StopAsyncIteration,\n", " 'StopIteration': StopIteration,\n", " 'GeneratorExit': GeneratorExit,\n", " 'SystemExit': SystemExit,\n", " 'KeyboardInterrupt': KeyboardInterrupt,\n", " 'ImportError': ImportError,\n", " 'ModuleNotFoundError': ModuleNotFoundError,\n", " 'OSError': OSError,\n", " 'EnvironmentError': OSError,\n", " 'IOError': OSError,\n", " 'EOFError': EOFError,\n", " 'RuntimeError': RuntimeError,\n", " 'RecursionError': RecursionError,\n", " 'NotImplementedError': NotImplementedError,\n", " 'NameError': NameError,\n", " 'UnboundLocalError': UnboundLocalError,\n", " 'AttributeError': AttributeError,\n", " 'SyntaxError': SyntaxError,\n", " 'IndentationError': IndentationError,\n", " 'TabError': TabError,\n", " 'LookupError': LookupError,\n", " 'IndexError': IndexError,\n", " 'KeyError': KeyError,\n", " 'ValueError': ValueError,\n", " 'UnicodeError': UnicodeError,\n", " 'UnicodeEncodeError': UnicodeEncodeError,\n", " 'UnicodeDecodeError': UnicodeDecodeError,\n", " 'UnicodeTranslateError': UnicodeTranslateError,\n", " 'AssertionError': AssertionError,\n", " 'ArithmeticError': ArithmeticError,\n", " 'FloatingPointError': FloatingPointError,\n", " 'OverflowError': OverflowError,\n", " 'ZeroDivisionError': ZeroDivisionError,\n", " 'SystemError': SystemError,\n", " 'ReferenceError': ReferenceError,\n", " 'MemoryError': MemoryError,\n", " 'BufferError': BufferError,\n", " 'Warning': Warning,\n", " 'UserWarning': UserWarning,\n", " 'DeprecationWarning': DeprecationWarning,\n", " 'PendingDeprecationWarning': PendingDeprecationWarning,\n", " 'SyntaxWarning': SyntaxWarning,\n", " 'RuntimeWarning': RuntimeWarning,\n", " 'FutureWarning': FutureWarning,\n", " 'ImportWarning': ImportWarning,\n", " 'UnicodeWarning': UnicodeWarning,\n", " 'BytesWarning': BytesWarning,\n", " 'ResourceWarning': ResourceWarning,\n", " 'ConnectionError': ConnectionError,\n", " 'BlockingIOError': BlockingIOError,\n", " 'BrokenPipeError': BrokenPipeError,\n", " 'ChildProcessError': ChildProcessError,\n", " 'ConnectionAbortedError': ConnectionAbortedError,\n", " 'ConnectionRefusedError': ConnectionRefusedError,\n", " 'ConnectionResetError': ConnectionResetError,\n", " 'FileExistsError': FileExistsError,\n", " 'FileNotFoundError': FileNotFoundError,\n", " 'IsADirectoryError': IsADirectoryError,\n", " 'NotADirectoryError': NotADirectoryError,\n", " 'InterruptedError': InterruptedError,\n", " 'PermissionError': PermissionError,\n", " 'ProcessLookupError': ProcessLookupError,\n", " 'TimeoutError': TimeoutError,\n", " 'open': ,\n", " 'copyright': Copyright (c) 2001-2020 Python Software Foundation.\n", " All Rights Reserved.\n", " \n", " Copyright (c) 2000 BeOpen.com.\n", " All Rights Reserved.\n", " \n", " Copyright (c) 1995-2001 Corporation for National Research Initiatives.\n", " All Rights Reserved.\n", " \n", " Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\n", " All Rights Reserved.,\n", " 'credits': Thanks to CWI, CNRI, BeOpen.com, Zope Corporation and a cast of thousands\n", " for supporting Python development. See www.python.org for more information.,\n", " 'license': Type license() to see the full license text,\n", " 'help': Type help() for interactive help, or help(object) for help about object.,\n", " '__IPYTHON__': True,\n", " 'display': ,\n", " 'get_ipython': >},\n", " '__all__': ['ascii_letters',\n", " 'ascii_lowercase',\n", " 'ascii_uppercase',\n", " 'capwords',\n", " 'digits',\n", " 'hexdigits',\n", " 'octdigits',\n", " 'printable',\n", " 'punctuation',\n", " 'whitespace',\n", " 'Formatter',\n", " 'Template'],\n", " '_string': ,\n", " 'whitespace': ' \\t\\n\\r\\x0b\\x0c',\n", " 'ascii_lowercase': 'abcdefghijklmnopqrstuvwxyz',\n", " 'ascii_uppercase': 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n", " 'ascii_letters': 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',\n", " 'digits': '0123456789',\n", " 'hexdigits': '0123456789abcdefABCDEF',\n", " 'octdigits': '01234567',\n", " 'punctuation': '!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~',\n", " 'printable': '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"#$%&\\'()*+,-./:;<=>?@[\\\\]^_`{|}~ \\t\\n\\r\\x0b\\x0c',\n", " 'capwords': ,\n", " '_re': ,\n", " '_ChainMap': collections.ChainMap,\n", " '_sentinel_dict': {},\n", " '_TemplateMetaclass': string._TemplateMetaclass,\n", " 'Template': string.Template,\n", " 'Formatter': string.Formatter}" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import string\n", "vars(string)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 13. \"__input__\"\n", "If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. " ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdin", "output_type": "stream", "text": [ "What is your name? Renato\n" ] } ], "source": [ "x = input('What is your name?')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 14. \"__any__\" and \"__all__\"" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "At least one True\n", "At least one True and one False\n" ] } ], "source": [ "x = [True, True, False]\n", "\n", "if any(x):\n", " print(\"At least one True\")\n", " \n", "if all(x):\n", " print(\"No one False\")\n", " \n", "if any(x) and not all(x):\n", " print(\"At least one True and one False\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__enumerate__\"" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 \t a\n", "1 \t \n", "2 \t s\n", "3 \t i\n", "4 \t n\n", "5 \t g\n", "6 \t l\n", "7 \t e\n", "8 \t \n", "9 \t t\n", "10 \t e\n", "11 \t x\n", "12 \t t\n" ] } ], "source": [ "for idx, letter in enumerate('a single text'):\n", " print(idx, '\\t', letter)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### [\"__eval__\"](https://www.programiz.com/python-programming/methods/built-in/eval) and [\"__exec__\"](https://www.programiz.com/python-programming/methods/built-in/exec)\n", "\n", "In simple terms, the eval() function runs the python code (which is passed as an argument) within the program. \n", "The syntax of eval() is: \n", "> eval(expression, globals=None, locals=None) \n", "\n", "The exec() method executes the dynamically created program, which is either a string or a code object.\n", "The syntax of exec():\n", "> exec(object, globals, locals) " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "eval('2<9')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def cal(a, b, op): \n", " return eval(f'{a} {op} {b}')\n", "\n", "cal('2','3','+')" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sum = 15\n" ] } ], "source": [ "program = 'a = 5\\nb=10\\nprint(\"Sum =\", a+b)'\n", "exec(program)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__iter__\" and \"__next__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__ascii__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__breakpoint__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__bytearray__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__bytes__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__compile__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__divmod__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__format__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__hash__\" \n", "+ Return the hash value of the object (if it has one). Hash values are integers." ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [], "source": [ "x = 'one string'\n", "y = 'one string'\n", "z = 'another string'" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5451647909180312000" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hash(x)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5451647909180312000" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hash(y)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-1125697929480386861" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "hash(z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__id__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__memoryview__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__object__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__property__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### \"__slice__\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.10" } }, "nbformat": 4, "nbformat_minor": 4 }