{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# CS 200: Introduction to Python\n", "\n", "\n", "

\n", "This notebook mirrors the google python course introduction." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

How to read this document

\n", "\n", "Well, first you should read it. OK? But you should also launch a Python window and type in the expressions. Learning a programming language is like learning to play a musical instrument. You don't learn to play the piano by just watching Horowitz or Billy Joel. You have to put your own hands on the keyboard.\n", "\n", "That's what you need to do now. Put your hands on the keyboard." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Python has Types but No Type Declarations\n", "\n", "Unlike C, Python variables (and functions) do not have type declarations. That is, you do not need to specify that x is an integer or a string or an array. The type(object) tells you the type of an object." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "a = 9" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "9" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(a)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "a = 'a string'" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(a)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(3.3)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "type" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(float)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Operator Overloading\n", "\n", "Python supports operator overloading. That is, the same operator can mean different things depending on the types of its operands. This is a key concept in object oriented programming, which is well-supported by Python.\n", "\n", "The + operator is overloaded.\n", "\n", "> int + int => addition\n", "\n", "> string + string => concatenation\n", "\n", "> int + string -> ERROR" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "a = 9 + 3" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "a = \"hello\" + \" world!\"" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello world!'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for +: 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "Input \u001b[0;32mIn [1]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;241m3\u001b[39m \u001b[38;5;241m+\u001b[39m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mhello\u001b[39m\u001b[38;5;124m\"\u001b[39m\n", "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" ] } ], "source": [ "3 + \"hello\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The * operator is overloaded as well.\n", "\n", "> int * int => multiplication\n", "\n", "> int * string => replication\n", "\n", "> string * int => replication" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "b = 3 * 4" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "b = 'hello ' * 3" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello hello hello '" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'good-bye good-bye good-bye good-bye '" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "4 * \"good-bye \"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Python Filename extensions

\n", "\n", "Python source code typically has the filename extension: \".py\"\n", "\n", "Compiled byte code typically has the filename extension \".pyc\"\n", "\n", "When you give the command import filename, python looks for the compiled file filename.pyc, but if it is not found, python loads the source code\n", "file, filename.py, and saves the bytecode file in the directory \\_\\_pycache\\_\\_ in the current working directory.\n", "\n", "### Executing Python files from the command line\n", "\n", "Following the standard UNIX convention, if the first two characters of a python file are \"#!\" (\"shuh-bang\") the remainder of the line is interpreted as the name of the program to be invoked in executing the remainder of the file. For example, if the first line is\n", "\n", "#! /usr/bin/python\n", "\n", "The python interpreter with that fully-qualified pathname will be executed on the current file. See collatz.py\n", "\n", "### Comment character\n", "\n", "# is the comment character in python. Everything to the right of the hash is ignored, unless the hash appears inside a string." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "# b = 'something else'" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'hello hello hello '" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "b = '#something else'" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'#something else'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### dir(module)\n", "\n", "dir(module) gives you the properties, methods, and other objects inside the given module.\n", "\n", "dir() lists the objects in the top-level \"main\" environment." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['In',\n", " 'Out',\n", " '_',\n", " '_10',\n", " '_3',\n", " '_5',\n", " '_6',\n", " '_8',\n", " '__',\n", " '___',\n", " '__builtin__',\n", " '__builtins__',\n", " '__doc__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__spec__',\n", " '_dh',\n", " '_i',\n", " '_i1',\n", " '_i10',\n", " '_i11',\n", " '_i2',\n", " '_i3',\n", " '_i4',\n", " '_i5',\n", " '_i6',\n", " '_i7',\n", " '_i8',\n", " '_i9',\n", " '_ih',\n", " '_ii',\n", " '_iii',\n", " '_oh',\n", " 'b',\n", " 'exit',\n", " 'get_ipython',\n", " 'quit',\n", " 'register_readline_completion',\n", " 'sys']" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir()" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'__main__'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "__name__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\\_\\_name\\_\\_ is the variable which holds the name string for the given module. Here is an example with the collatz module." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [], "source": [ "import collatz" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__builtins__',\n", " '__cached__',\n", " '__doc__',\n", " '__file__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__spec__',\n", " 'collatz',\n", " 'collatzg',\n", " 'cseries']" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(collatz)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'collatz'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "collatz.__name__" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/home/httpd/html/zoo/classes/cs200/lectures/collatz.py'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "collatz.__file__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### command line arguments\n", "\n", "collatz.py included the following code:\n", "\n", "
\n",
    "if __name__ == '__main__':\n",
    "    import sys\n",
    "    print (sys.argv)\n",
    "    if len(sys.argv) > 1:\n",
    "        for n in sys.argv[1:]:\n",
    "            cseries(int(n))\n",
    "
\n", "\n", "We import the sys module, which has the argv property which is a list of the command line arguments.\n", "\n", "(Note that Jupyter notebooks do not support command line arguments.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### function definition\n", "\n", "Use the def keyword to define functions in Python. Use indentation to specify blocks of code. You do not use parens or curly brackets." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "def add1(n):\n", " return n + 1" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "add1(9)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [], "source": [ "def bad1(n):\n", " return x+1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that there is an error in the definition. However, the error is not caught at compile time. When you run it though, the error throws a NameError exception." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'x' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "Input \u001b[0;32mIn [20]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m bad1(\u001b[38;5;241m3\u001b[39m)\n", "Input \u001b[0;32mIn [19]\u001b[0m, in \u001b[0;36mbad1\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mbad1\u001b[39m(n):\n\u001b[0;32m----> 2\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mx\u001b[49m\u001b[38;5;241m+\u001b[39m\u001b[38;5;241m1\u001b[39m\n", "\u001b[0;31mNameError\u001b[0m: name 'x' is not defined" ] } ], "source": [ "bad1(3)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "x = 3" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bad1(4)" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Syntax errors versus Runtime errors\n", "\n", "Some errors are detected at compile time, namely, syntax errors. If you enter an illegal Python expression, Python will complain." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (1057635366.py, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m Input \u001b[0;32mIn [24]\u001b[0;36m\u001b[0m\n\u001b[0;31m l l = 8\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "l l = 8" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (59284081.py, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m Input \u001b[0;32mIn [25]\u001b[0;36m\u001b[0m\n\u001b[0;31m l = 8 8 8\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "l = 8 8 8" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (37543656.py, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m Input \u001b[0;32mIn [26]\u001b[0;36m\u001b[0m\n\u001b[0;31m x =-=-- 9\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "x =-=-- 9" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (536496293.py, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m Input \u001b[0;32mIn [27]\u001b[0;36m\u001b[0m\n\u001b[0;31m def add1(n)::\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "def add1(n)::\n", " return n+1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Python PEP documents and modules\n", "\n", "Python is a crowdsourced language. There are lots of developers. When someone wants to modify the language, they create a \"Python Enhancement Proposal\" or PEP, which are given sequential positive integers. PEP8 (https://www.python.org/dev/peps/pep-0008/) is the Style Guide for Python Code. Check it out." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Developers not only modify the Python language, they also create boatloads of useful modules. The standard modules are in the library: (https://docs.python.org/3/library/)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Online help\n", "\n", "There are lots of ways to get help for python.\n", "\n", "> google. e.g., search for python string lowercase\n", "\n", "> The python website: (https://docs.python.org/3/)\n", "\n", "> StackOverflow: (https://stackoverflow.com/questions/tagged/python)\n", "\n", "as well as the help() and dir() functions inside python" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function len in module builtins:\n", "\n", "len(obj, /)\n", " Return the number of items in a container.\n", "\n" ] } ], "source": [ "help(len)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len('hello')" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(range(10))" ] }, { "cell_type": "code", "execution_count": 31, "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": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in module sys:\n", "\n", "NAME\n", " sys\n", "\n", "MODULE REFERENCE\n", " https://docs.python.org/3.10/library/sys.html\n", " \n", " The following documentation is automatically generated from the Python\n", " source files. It may be incomplete, incorrect or include features that\n", " are considered implementation detail and may vary between Python\n", " implementations. When in doubt, consult the module reference at the\n", " location listed above.\n", "\n", "DESCRIPTION\n", " This module provides access to some objects used or maintained by the\n", " interpreter and to functions that interact strongly with the interpreter.\n", " \n", " Dynamic objects:\n", " \n", " argv -- command line arguments; argv[0] is the script pathname if known\n", " path -- module search path; path[0] is the script directory, else ''\n", " modules -- dictionary of loaded modules\n", " \n", " displayhook -- called to show results in an interactive session\n", " excepthook -- called to handle any uncaught exception other than SystemExit\n", " To customize printing in an interactive session or to install a custom\n", " top-level exception handler, assign other functions to replace these.\n", " \n", " stdin -- standard input file object; used by input()\n", " stdout -- standard output file object; used by print()\n", " stderr -- standard error object; used for error messages\n", " By assigning other file objects (or objects that behave like files)\n", " to these, it is possible to redirect all of the interpreter's I/O.\n", " \n", " last_type -- type of last uncaught exception\n", " last_value -- value of last uncaught exception\n", " last_traceback -- traceback of last uncaught exception\n", " These three are only available in an interactive session after a\n", " traceback has been printed.\n", " \n", " Static objects:\n", " \n", " builtin_module_names -- tuple of module names built into this interpreter\n", " copyright -- copyright notice pertaining to this interpreter\n", " exec_prefix -- prefix used to find the machine-specific Python library\n", " executable -- absolute path of the executable binary of the Python interpreter\n", " float_info -- a named tuple with information about the float implementation.\n", " float_repr_style -- string indicating the style of repr() output for floats\n", " hash_info -- a named tuple with information about the hash algorithm.\n", " hexversion -- version information encoded as a single integer\n", " implementation -- Python implementation information.\n", " int_info -- a named tuple with information about the int implementation.\n", " maxsize -- the largest supported length of containers.\n", " maxunicode -- the value of the largest Unicode code point\n", " platform -- platform identifier\n", " prefix -- prefix used to find the Python library\n", " thread_info -- a named tuple with information about the thread implementation.\n", " version -- the version of this interpreter as a string\n", " version_info -- version information as a named tuple\n", " __stdin__ -- the original stdin; don't touch!\n", " __stdout__ -- the original stdout; don't touch!\n", " __stderr__ -- the original stderr; don't touch!\n", " __displayhook__ -- the original displayhook; don't touch!\n", " __excepthook__ -- the original excepthook; don't touch!\n", " \n", " Functions:\n", " \n", " displayhook() -- print an object to the screen, and save it in builtins._\n", " excepthook() -- print an exception and its traceback to sys.stderr\n", " exc_info() -- return thread-safe information about the current exception\n", " exit() -- exit the interpreter by raising SystemExit\n", " getdlopenflags() -- returns flags to be used for dlopen() calls\n", " getprofile() -- get the global profiling function\n", " getrefcount() -- return the reference count for an object (plus one :-)\n", " getrecursionlimit() -- return the max recursion depth for the interpreter\n", " getsizeof() -- return the size of an object in bytes\n", " gettrace() -- get the global debug tracing function\n", " setdlopenflags() -- set the flags to be used for dlopen() calls\n", " setprofile() -- set the global profiling function\n", " setrecursionlimit() -- set the max recursion depth for the interpreter\n", " settrace() -- set the global debug tracing function\n", "\n", "FUNCTIONS\n", " __breakpointhook__ = breakpointhook(...)\n", " breakpointhook(*args, **kws)\n", " \n", " This hook function is called by built-in breakpoint().\n", " \n", " __displayhook__ = displayhook(object, /)\n", " Print an object to sys.stdout and also save it in builtins._\n", " \n", " __excepthook__ = excepthook(exctype, value, traceback, /)\n", " Handle an exception by displaying it with a traceback on sys.stderr.\n", " \n", " __unraisablehook__ = unraisablehook(unraisable, /)\n", " Handle an unraisable exception.\n", " \n", " The unraisable argument has the following attributes:\n", " \n", " * exc_type: Exception type.\n", " * exc_value: Exception value, can be None.\n", " * exc_traceback: Exception traceback, can be None.\n", " * err_msg: Error message, can be None.\n", " * object: Object causing the exception, can be None.\n", " \n", " addaudithook(hook)\n", " Adds a new audit hook callback.\n", " \n", " audit(...)\n", " audit(event, *args)\n", " \n", " Passes the event to any audit hooks that are attached.\n", " \n", " breakpointhook(...)\n", " breakpointhook(*args, **kws)\n", " \n", " This hook function is called by built-in breakpoint().\n", " \n", " call_tracing(func, args, /)\n", " Call func(*args), while tracing is enabled.\n", " \n", " The tracing state is saved, and restored afterwards. This is intended\n", " to be called from a debugger from a checkpoint, to recursively debug\n", " some other code.\n", " \n", " exc_info()\n", " Return current exception information: (type, value, traceback).\n", " \n", " Return information about the most recent exception caught by an except\n", " clause in the current stack frame or in an older stack frame.\n", " \n", " exit(status=None, /)\n", " Exit the interpreter by raising SystemExit(status).\n", " \n", " If the status is omitted or None, it defaults to zero (i.e., success).\n", " If the status is an integer, it will be used as the system exit status.\n", " If it is another kind of object, it will be printed and the system\n", " exit status will be one (i.e., failure).\n", " \n", " get_asyncgen_hooks()\n", " Return the installed asynchronous generators hooks.\n", " \n", " This returns a namedtuple of the form (firstiter, finalizer).\n", " \n", " get_coroutine_origin_tracking_depth()\n", " Check status of origin tracking for coroutine objects in this thread.\n", " \n", " getallocatedblocks()\n", " Return the number of memory blocks currently allocated.\n", " \n", " getdefaultencoding()\n", " Return the current default encoding used by the Unicode implementation.\n", " \n", " getdlopenflags()\n", " Return the current value of the flags that are used for dlopen calls.\n", " \n", " The flag constants are defined in the os module.\n", " \n", " getfilesystemencodeerrors()\n", " Return the error mode used Unicode to OS filename conversion.\n", " \n", " getfilesystemencoding()\n", " Return the encoding used to convert Unicode filenames to OS filenames.\n", " \n", " getprofile()\n", " Return the profiling function set with sys.setprofile.\n", " \n", " See the profiler chapter in the library manual.\n", " \n", " getrecursionlimit()\n", " Return the current value of the recursion limit.\n", " \n", " The recursion limit is the maximum depth of the Python interpreter\n", " stack. This limit prevents infinite recursion from causing an overflow\n", " of the C stack and crashing Python.\n", " \n", " getrefcount(object, /)\n", " Return the reference count of object.\n", " \n", " The count returned is generally one higher than you might expect,\n", " because it includes the (temporary) reference as an argument to\n", " getrefcount().\n", " \n", " getsizeof(...)\n", " getsizeof(object [, default]) -> int\n", " \n", " Return the size of object in bytes.\n", " \n", " getswitchinterval()\n", " Return the current thread switch interval; see sys.setswitchinterval().\n", " \n", " gettrace()\n", " Return the global debug tracing function set with sys.settrace.\n", " \n", " See the debugger chapter in the library manual.\n", " \n", " intern(string, /)\n", " ``Intern'' the given string.\n", " \n", " This enters the string in the (global) table of interned strings whose\n", " purpose is to speed up dictionary lookups. Return the string itself or\n", " the previously interned string object with the same value.\n", " \n", " is_finalizing()\n", " Return True if Python is exiting.\n", " \n", " set_asyncgen_hooks(...)\n", " set_asyncgen_hooks(* [, firstiter] [, finalizer])\n", " \n", " Set a finalizer for async generators objects.\n", " \n", " set_coroutine_origin_tracking_depth(depth)\n", " Enable or disable origin tracking for coroutine objects in this thread.\n", " \n", " Coroutine objects will track 'depth' frames of traceback information\n", " about where they came from, available in their cr_origin attribute.\n", " \n", " Set a depth of 0 to disable.\n", " \n", " setdlopenflags(flags, /)\n", " Set the flags used by the interpreter for dlopen calls.\n", " \n", " This is used, for example, when the interpreter loads extension\n", " modules. Among other things, this will enable a lazy resolving of\n", " symbols when importing a module, if called as sys.setdlopenflags(0).\n", " To share symbols across extension modules, call as\n", " sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag\n", " modules can be found in the os module (RTLD_xxx constants, e.g.\n", " os.RTLD_LAZY).\n", " \n", " setprofile(...)\n", " setprofile(function)\n", " \n", " Set the profiling function. It will be called on each function call\n", " and return. See the profiler chapter in the library manual.\n", " \n", " setrecursionlimit(limit, /)\n", " Set the maximum depth of the Python interpreter stack to n.\n", " \n", " This limit prevents infinite recursion from causing an overflow of the C\n", " stack and crashing Python. The highest possible limit is platform-\n", " dependent.\n", " \n", " setswitchinterval(interval, /)\n", " Set the ideal thread switching delay inside the Python interpreter.\n", " \n", " The actual frequency of switching threads can be lower if the\n", " interpreter executes long sequences of uninterruptible code\n", " (this is implementation-specific and workload-dependent).\n", " \n", " The parameter must represent the desired switching delay in seconds\n", " A typical value is 0.005 (5 milliseconds).\n", " \n", " settrace(...)\n", " settrace(function)\n", " \n", " Set the global debug tracing function. It will be called on each\n", " function call. See the debugger chapter in the library manual.\n", " \n", " unraisablehook(unraisable, /)\n", " Handle an unraisable exception.\n", " \n", " The unraisable argument has the following attributes:\n", " \n", " * exc_type: Exception type.\n", " * exc_value: Exception value, can be None.\n", " * exc_traceback: Exception traceback, can be None.\n", " * err_msg: Error message, can be None.\n", " * object: Object causing the exception, can be None.\n", "\n", "DATA\n", " __stderr__ = <_io.TextIOWrapper name='' mode='w' encoding='utf...\n", " __stdin__ = <_io.TextIOWrapper name='' mode='r' encoding='utf-8...\n", " __stdout__ = <_io.TextIOWrapper name='' mode='w' encoding='utf...\n", " abiflags = ''\n", " api_version = 1013\n", " argv = ['/usr/lib/python3.10/site-packages/ipykernel_launcher.py', '-f...\n", " base_exec_prefix = '/usr'\n", " base_prefix = '/usr'\n", " builtin_module_names = ('_abc', '_ast', '_codecs', '_collections', '_f...\n", " byteorder = 'little'\n", " copyright = 'Copyright (c) 2001-2022 Python Software Foundati...ematis...\n", " displayhook = \n", " dont_write_bytecode = False\n", " exec_prefix = '/usr'\n", " executable = '/usr/bin/python3'\n", " flags = sys.flags(debug=0, inspect=0, interactive=0, opt...mode=False,...\n", " float_info = sys.float_info(max=1.7976931348623157e+308, max_...epsilo...\n", " float_repr_style = 'short'\n", " hash_info = sys.hash_info(width=64, modulus=2305843009213693...iphash2...\n", " hexversion = 50988528\n", " implementation = namespace(name='cpython', cache_tag='cpython-310...xv...\n", " int_info = sys.int_info(bits_per_digit=30, sizeof_digit=4)\n", " last_value = SyntaxError('invalid syntax', ('/tmp/ipykernel_4.../53649...\n", " maxsize = 9223372036854775807\n", " maxunicode = 1114111\n", " meta_path = [, , \n", " stdin = <_io.TextIOWrapper name='' mode='r' encoding='utf-8'>\n", " stdlib_module_names = frozenset({'__future__', '_abc', '_aix_support',...\n", " stdout = \n", " thread_info = sys.thread_info(name='pthread', lock='semaphore', versio...\n", " version = '3.10.5 (main, Jun 9 2022, 00:00:00) [GCC 12.1.1 20220507 (...\n", " version_info = sys.version_info(major=3, minor=10, micro=5, releaselev...\n", " warnoptions = []\n", "\n", "FILE\n", " (built-in)\n", "\n", "\n" ] } ], "source": [ "help(sys)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function dir in module builtins:\n", "\n", "dir(...)\n", " dir([object]) -> list of strings\n", " \n", " If called without an argument, return the names in the current scope.\n", " Else, return an alphabetized list of names comprising (some of) the attributes\n", " of the given object, and of attributes reachable from it.\n", " If the object supplies a method named __dir__, it will be used; otherwise\n", " the default dir() logic is used and returns:\n", " for a module object: the module's attributes.\n", " for a class object: its attributes, and recursively the attributes\n", " of its bases.\n", " for any other object: its attributes, its class's attributes, and\n", " recursively the attributes of its class's base classes.\n", "\n" ] } ], "source": [ "help(dir)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__breakpointhook__',\n", " '__displayhook__',\n", " '__doc__',\n", " '__excepthook__',\n", " '__interactivehook__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__spec__',\n", " '__stderr__',\n", " '__stdin__',\n", " '__stdout__',\n", " '__unraisablehook__',\n", " '_base_executable',\n", " '_clear_type_cache',\n", " '_current_exceptions',\n", " '_current_frames',\n", " '_deactivate_opcache',\n", " '_debugmallocstats',\n", " '_framework',\n", " '_getframe',\n", " '_git',\n", " '_home',\n", " '_xoptions',\n", " 'abiflags',\n", " 'addaudithook',\n", " 'api_version',\n", " 'argv',\n", " 'audit',\n", " 'base_exec_prefix',\n", " 'base_prefix',\n", " 'breakpointhook',\n", " 'builtin_module_names',\n", " 'byteorder',\n", " 'call_tracing',\n", " 'copyright',\n", " 'displayhook',\n", " 'dont_write_bytecode',\n", " 'exc_info',\n", " 'excepthook',\n", " 'exec_prefix',\n", " 'executable',\n", " 'exit',\n", " 'flags',\n", " 'float_info',\n", " 'float_repr_style',\n", " 'get_asyncgen_hooks',\n", " 'get_coroutine_origin_tracking_depth',\n", " 'getallocatedblocks',\n", " 'getdefaultencoding',\n", " 'getdlopenflags',\n", " 'getfilesystemencodeerrors',\n", " 'getfilesystemencoding',\n", " 'getprofile',\n", " 'getrecursionlimit',\n", " 'getrefcount',\n", " 'getsizeof',\n", " 'getswitchinterval',\n", " 'gettrace',\n", " 'hash_info',\n", " 'hexversion',\n", " 'implementation',\n", " 'int_info',\n", " 'intern',\n", " 'is_finalizing',\n", " 'last_traceback',\n", " 'last_type',\n", " 'last_value',\n", " 'maxsize',\n", " 'maxunicode',\n", " 'meta_path',\n", " 'modules',\n", " 'orig_argv',\n", " 'path',\n", " 'path_hooks',\n", " 'path_importer_cache',\n", " 'platform',\n", " 'platlibdir',\n", " 'prefix',\n", " 'ps1',\n", " 'ps2',\n", " 'ps3',\n", " 'pycache_prefix',\n", " 'set_asyncgen_hooks',\n", " 'set_coroutine_origin_tracking_depth',\n", " 'setdlopenflags',\n", " 'setprofile',\n", " 'setrecursionlimit',\n", " 'setswitchinterval',\n", " 'settrace',\n", " 'stderr',\n", " 'stdin',\n", " 'stdlib_module_names',\n", " 'stdout',\n", " 'thread_info',\n", " 'unraisablehook',\n", " 'version',\n", " 'version_info',\n", " 'warnoptions']" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(sys)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [], "source": [ "import collatz" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__builtins__',\n", " '__cached__',\n", " '__doc__',\n", " '__file__',\n", " '__loader__',\n", " '__name__',\n", " '__package__',\n", " '__spec__',\n", " 'collatz',\n", " 'collatzg',\n", " 'cseries']" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(collatz)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'collatz'" ] }, "execution_count": 45, "metadata": {}, "output_type": "execute_result" } ], "source": [ "collatz.__name__" ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "" ] }, "execution_count": 46, "metadata": {}, "output_type": "execute_result" } ], "source": [ "collatz.cseries" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "16\n", "8\n", "4\n", "2\n", "1\n", "done\n" ] } ], "source": [ "collatz.cseries(16)" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/home/httpd/html/zoo/classes/cs200/lectures/collatz.py'" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "collatz.__file__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "End of Introduction notebook.\n", "\n", "

\n", "" ] } ], "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.10.5" } }, "nbformat": 4, "nbformat_minor": 4 }