{ "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": [ "
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;36mimport 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;36mpython 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='