{"id":2104,"date":"2011-03-30T15:09:37","date_gmt":"2011-03-30T20:09:37","guid":{"rendered":"http:\/\/jianmingli.com\/wp\/?p=2104"},"modified":"2015-06-02T14:27:46","modified_gmt":"2015-06-02T19:27:46","slug":"python","status":"publish","type":"post","link":"https:\/\/jianmingli.com\/wp\/?p=2104","title":{"rendered":"Python"},"content":{"rendered":"<div class='toc wptoc'>\n<h2>Contents<\/h2>\n<ol class='toc-odd level-1'>\n\t<li>\n\t\t<a href=\"#Overview\">Overview<\/a>\n\t\t<ol class='toc-even level-2'>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Used_For\">Used For<\/a>\n\t\t\t<\/li>\n\t\t<\/ol>\n\t<li>\n\t\t<a href=\"#Install_Python_3.2\">Install Python 3.2<\/a>\n\t\t<ol class='toc-even level-2'>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Windows\">Windows<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Cygwin\">Cygwin<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Unix\">Unix<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Misc\">Misc<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Listing_functions_in_a_module\">Listing functions in a module<\/a>\n\t\t\t<\/li>\n\t\t<\/ol>\n\t<li>\n\t\t<a href=\"#Data_Types\">Data Types<\/a>\n\t\t<ol class='toc-even level-2'>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Strings\">Strings<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Type_conversion\">Type conversion<\/a>\n\t\t\t<\/li>\n\t\t<\/ol>\n\t<li>\n\t\t<a href=\"#Variables_and_Values\">Variables and Values<\/a>\n\t\t<ol class='toc-even level-2'>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Reading_Strings_from_the_Keyboard\">Reading Strings from the Keyboard<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Boolean_Logic\">Boolean Logic<\/a>\n\t\t\t<\/li>\n\t\t<\/ol>\n\t<li>\n\t\t<a href=\"#Functions\">Functions<\/a>\n\t\t<ol class='toc-even level-2'>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Define_Functions\">Define Functions<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#main_Function\">main() Function<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Variable_Scope\">Variable Scope<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Function_Parameters\">Function Parameters<\/a>\n\t\t\t<\/li>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Modules\">Modules<\/a>\n\t\t\t\t<ol class='toc-odd level-3'>\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<a href=\"#Namespace\">Namespace<\/a>\n\t\t\t\t\t<\/li>\n\t\t\t\t<\/ol>\n<\/ol>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Strings_1\">Strings<\/a>\n\t\t\t\t<ol class='toc-even level-2'>\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<a href=\"#Characters\">Characters<\/a>\n\t\t\t\t\t<\/li>\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<a href=\"#Standard_String_Functions\">Standard String Functions<\/a>\n\t\t\t\t\t<\/li>\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<a href=\"#Regular_Expression\">Regular Expression<\/a>\n\t\t\t\t\t<\/li>\n\t\t\t\t<\/ol>\n\t\t\t<li>\n\t\t\t\t<a href=\"#Data_Structure\">Data Structure<\/a>\n\t\t\t\t<ol class='toc-even level-2'>\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<a href=\"#Sequence_Types\">Sequence Types<\/a>\n\t\t\t\t\t\t<ol class='toc-odd level-3'>\n\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t<a href=\"#Tuples\">Tuples<\/a>\n\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t<a href=\"#Lists\">Lists<\/a>\n\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t<a href=\"#Dictionaries\">Dictionaries<\/a>\n\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t<a href=\"#Sets\">Sets<\/a>\n\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t<\/ol>\n<\/ol>\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<a href=\"#IO\">IO<\/a>\n\t\t\t\t\t\t<ol class='toc-even level-2'>\n\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t<a href=\"#Format_Strings\">Format Strings<\/a>\n\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t<a href=\"#File_IO\">File IO<\/a>\n\t\t\t\t\t\t\t\t<ol class='toc-odd level-3'>\n\t\t\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t\t\t<a href=\"#Listing_files\">Listing files<\/a>\n\t\t\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t\t\t<a href=\"#File_modes\">File modes<\/a>\n\t\t\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t\t\t<a href=\"#Text_files\">Text files<\/a>\n\t\t\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t\t\t<a href=\"#Binary_File\">Binary File<\/a>\n\t\t\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t\t\t<a href=\"#Pickling\">Pickling<\/a>\n\t\t\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t\t\t<a href=\"#Read_Web_Page_with_urllib\">Read Web Page with urllib<\/a>\n\t\t\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t\t<\/ol>\n<\/ol>\n\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t<a href=\"#Exception_Handling\">Exception Handling<\/a>\n\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t<a href=\"#OOP\">OOP<\/a>\n\t\t\t\t\t\t\t\t<ol class='toc-even level-2'>\n\t\t\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t\t\t<a href=\"#Class\">Class<\/a>\n\t\t\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t\t\t<a href=\"#Inheritance\">Inheritance<\/a>\n\t\t\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t\t\t<a href=\"#Polymorphism\">Polymorphism<\/a>\n\t\t\t\t\t\t\t\t\t<\/li>\n\t\t\t\t\t\t\t\t<\/ol>\n\t\t\t\t\t\t\t<li>\n\t\t\t\t\t\t\t\t<a href=\"#References\">References<\/a>\n\t\t\t\t\t\t\t<\/li>\n<\/ol>\n<\/ol>\n<\/div>\n<div class='wptoc-end'>&nbsp;<\/div>\n<span id=\"Overview\"><h2>Overview<\/h2><\/span>\n<p>* Started by Guido van Rossum<br \/>\n* Named after Morty Python comedy troupe<br \/>\n* Supports OOP (No interface support)<br \/>\n* No curly brackets, colon sign and indentation are used instead<br \/>\n* Statement indentations are <em>significant <\/em>in Python.<br \/>\n&#8211; <strong>Don&#8217;t<\/strong> mix spaces and tabs for indentations.<br \/>\n&#8211; See <a href=\"http:\/\/www.secnetix.de\/olli\/Python\/block_indentation.hawk\">this post<\/a> for details.<br \/>\n* No semicolon to terminate statements<br \/>\n* Comment char is #<br \/>\n* Escape char is \\<\/p>\n<span id=\"Used_For\"><h3>Used For<\/h3><\/span>\n<p>* Scripts<br \/>\n* Web development<br \/>\n&#8211; Django<br \/>\n&#8211; Turbo Gears<br \/>\n&#8211; Zope<br \/>\n* Text processing<br \/>\n* Scientific computing<br \/>\n* Education<\/p>\n<span id=\"Install_Python_3.2\"><h2>Install Python 3.2<\/h2><\/span>\n<p>* <a href=\"http:\/\/www.python.org\/getit\/releases\/3.2\/\">Download site<\/a><\/p>\n<span id=\"Windows\"><h3>Windows<\/h3><\/span>\n<p>* Go to download site and download<br \/>\n&#8211; <a href=\"http:\/\/www.python.org\/ftp\/python\/3.2\/python-3.2.msi\">Windows x86 MSI Installer (3.2)<\/a><br \/>\n* Double click the installer file to start the installer<br \/>\n&#8211; Install for all users<br \/>\n&#8211; Destination directory: C:\\Python32\\<br \/>\n&#8211; Accept defaults on Customize screen<br \/>\n* Start command line<\/p>\n<pre lang=\"python\">\r\ncd C:\\Python32\r\nC:\\Python32>python\r\nPython 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32\r\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\r\n>>> 2 * 3\r\n6\r\n>>>\r\n<\/pre>\n<p>* Start command line<br \/>\nstart -> All Programs -> Python 3.2 -> Python (command line)<\/p>\n<p>* Start GUI<br \/>\nstart -> All Programs -> Python 3.2 -> IDLE (Python GUI)<\/p>\n<span id=\"Cygwin\"><h3>Cygwin<\/h3><\/span>\n<p>* Use Cygwin setup.exe program<br \/>\n* Select install Python<br \/>\n* Start  command line<\/p>\n<pre lang=\"python\">\r\n$ python\r\nPython 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)\r\n[GCC 4.3.4 20090804 (release) 1] on cygwin\r\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\r\n>>> 2*3\r\n6\r\n>>>\r\n<\/pre>\n<span id=\"Unix\"><h3>Unix<\/h3><\/span>\n<p>\/\/TODO<\/p>\n<span id=\"Misc\"><h3>Misc<\/h3><\/span>\n<p>* Comments<\/p>\n<pre lang=\"python\">\r\n# This is a comment\r\n<\/pre>\n<span id=\"Listing_functions_in_a_module\"><h3>Listing functions in a module<\/h3><\/span>\n<pre lang=\"python\">\r\n# list math functions\r\nimport math\r\ndir(math)\r\n\r\n# list all builtin functions\r\ndir(__builtins__)\r\n\r\n# print function help\r\nhelp(f)\r\n\r\n# print doc string\r\nprint(math.tanh.__doc__)\r\nprint(bin.__doc__)\r\n<\/pre>\n<span id=\"Data_Types\"><h2>Data Types<\/h2><\/span>\n<span id=\"Strings\"><h3>Strings<\/h3><\/span>\n<p>* Denote a string<\/p>\n<pre lang=\"python\">\r\n# Single quotes: \r\n'this is a string'\r\n\r\n# Double quotes: \r\n\"this is a string\"\r\n\r\n# Triple quotes for multiline strings:\r\n\"\"\"This is\r\na multiline\r\nstring\r\n\"\"\"\r\n\r\n# Raw string\r\nr'c:\\Program Files\\python'\r\n<\/pre>\n<p>* String concatenation<\/p>\n<pre lang=\"python\">\r\n'string 1' + 'string 2'\r\n\r\n5 * 'hi' # hihihihihi\r\n\r\n'ha' * 5 # hahahahaha\r\n<\/pre>\n<span id=\"Type_conversion\"><h3>Type conversion<\/h3><\/span>\n<p>* Integer and strings -> floats: use float() function<\/p>\n<pre lang=\"python\">\r\nfloat(3)\r\n\r\nfloat('3.2')\r\n<\/pre>\n<p>* Integer and floats -> strings: use str(n) function<\/p>\n<pre lang=\"python\">\r\nstr(10)\r\nstr(-1.1)\r\n<\/pre>\n<p>* Float -> integer: use int() or round() functions<\/p>\n<pre lang=\"python\">\r\nint(1.52)\r\n1\r\nround (1.52)\r\n2\r\n<\/pre>\n<span id=\"Variables_and_Values\"><h2>Variables and Values<\/h2><\/span>\n<p>* Variable points to a value.<br \/>\n* Assignments don&#8217;t copy<br \/>\n * Numbers and strings are immutable<\/p>\n<pre lang=\"python\">\r\n# assignment\r\nvar1 = \"value1\"\r\n\r\n# multiple assignment\r\nx, y, z = 1, 'two', 3.0\r\n\r\n# swapping var values\r\na, b = 6, 7\r\na, b\r\n(6, 7)\r\na, b = b, a\r\na, b\r\n(7, 6)\r\n<\/pre>\n<span id=\"Reading_Strings_from_the_Keyboard\"><h3>Reading Strings from the Keyboard<\/h3><\/span>\n<pre lang=\"python\">\r\nname = input('What is your name? ')\r\nprint('Hello ' + name + '!')\r\n<\/pre>\n<span id=\"Boolean_Logic\"><h3>Boolean Logic<\/h3><\/span>\n<p>* Boolean values<\/p>\n<pre lang=\"python\">\r\nTrue\r\nFalse\r\n<\/pre>\n<p>* Logical operators<\/p>\n<pre lang=\"python\">\r\nnot\r\nand\r\nor\r\n==\r\n<\/pre>\n<p>* If\/else<\/p>\n<pre lang=\"python\">\r\npwd = input('What is the password? ')\r\nif pwd == 'apple':\r\n  print('ok')\r\nelse:\r\n  print('wrong password')\r\n<\/pre>\n<p>* if\/elif<\/p>\n<pre lang=\"python\">\r\nif pwd == 'apple':\r\n  print('ok')\r\nelif pwd == 'peach'\r\n  print('not bad')\r\nelse:\r\n  print('not good')\r\n<\/pre>\n<p>* Conditional expression<\/p>\n<pre lang=\"python\">\r\nfood = input(\"What\u2019 s your favorite food? \")\r\nreply = 'yuck' if food == 'lamb' else 'yum'\r\n<\/pre>\n<p>* For loops<\/p>\n<pre lang=\"python\">\r\n# count 0 to 9\r\nfor i in range(10):\r\n  print(i)\r\n\r\n# count 1 to 5\r\nfor i in range(1, 5):\r\n  print(i)\r\n\r\n# count from 5 to 1\r\nfor i in range(1, 5, -1):\r\n  print(i)\r\n<\/pre>\n<p>* While loops<\/p>\n<pre lang=\"python\">\r\ni = 0\r\nwhile i < 10:\r\n  print(i)\r\n  i = i + 1\r\n<\/pre>\n<p>* Break out of loop: break<\/p>\n<span id=\"Functions\"><h2>Functions<\/h2><\/span>\n<span id=\"Define_Functions\"><h3>Define Functions<\/h3><\/span>\n<pre lang=\"python\">\r\ndef area(radius):\r\n  \"\"\"\r\n    ==== Function doc ====\r\n    Usage: area(radius)\r\n  \"\"\"\r\n  import math\r\n  return math.pi * radius ** 2\r\n<\/pre>\n<span id=\"main_Function\"><h3>main() Function<\/h3><\/span>\n<p>* No mandatory main() function<br \/>\n* Good practice to have a main() function<br \/>\n* Need implicit call to main() function to invoke it<\/p>\n<span id=\"Variable_Scope\"><h3>Variable Scope<\/h3><\/span>\n<p>* All variables used within functions are local<br \/>\n* Global variables need to be re-declared within functions<\/p>\n<pre lang=\"python\">\r\nname = 'Jack'\r\ndef sayhi():\r\n    print('Hi, ' + name + '!')\r\n\r\ndef changeName(new_name):\r\n    global name\r\n    name = new_name\r\n    \r\nsayhi()\r\nchangeName('Jim')\r\nsayhi()\r\n\r\n>>> \r\nHi, Jack!\r\nHi, Jim!\r\n>>> \r\n<\/pre>\n<span id=\"Function_Parameters\"><h3>Function Parameters<\/h3><\/span>\n<p>* Function parameters are passed by object reference (see <a href=\"http:\/\/robertheaton.com\/2014\/02\/09\/pythons-pass-by-object-reference-as-explained-by-philip-k-dick\/\">this post<\/a> for details)<br \/>\n* Assign default parameter value<\/p>\n<pre lang=\"python\">\r\nname = 'Jim'\r\n\r\ndef sayhi2(name, greeting = 'Hi'):\r\n  print(greeting + ' ' + name + '!')\r\n\r\nsayhi2(name)\r\nsayhi2(name, 'Howdi')\r\n>>> \r\nHi Jim!\r\nHowdi Jim!\r\n>>> \r\n<\/pre>\n<p>* Keyword parameters<br \/>\n- All parameters need to have default values<\/p>\n<pre lang=\"python\">\r\ndef sayhi3(name = 'Jane', \r\n                 greeting = 'Hi'):\r\n    print(greeting + ' ' + name + '!')\r\n    \r\nsayhi3(greeting = 'Nihao')\r\n>>> \r\nNihao Jane!\r\n>>> \r\n<\/pre>\n<p>- Create a new object each time function is called by assigning a default '<em>None<\/em>' value to argument (see <a href=\"http:\/\/docs.python-guide.org\/en\/latest\/writing\/gotchas\/\">this post<\/a> for details):<\/p>\n<pre lang=\"python\">\r\ndef append_to(element, to=None):\r\n    if to is None:\r\n        to = []\r\n    to.append(element)\r\n    return to\r\n\r\nmy_list = append_to(12)\r\nprint my_list\r\n\r\nmy_other_list = append_to(42)\r\nprint my_other_list\r\n>>>[12]\r\n>>>[42]\r\n<\/pre>\n<span id=\"Modules\"><h3>Modules<\/h3><\/span>\n<p>* A module is just another Python source file<br \/>\n* A module contains a collection of functions and assignments<br \/>\n* See <a href=\"http:\/\/stackoverflow.com\/questions\/67631\/how-to-import-a-module-given-the-full-path\">this discussion<\/a> on how to include another python file<br \/>\n* For example,<\/p>\n<pre lang=\"python\">\r\nac1file = '.\/ac1.py'\r\nexecfile(ac1file)\r\n<\/pre>\n<pre lang=\"python\">\r\n\"\"\"\r\nA test module\r\n\"\"\"\r\n\r\ndef sayhi(name):\r\n  \"\"\"\r\n  Simple hi\r\n  \"\"\"\r\n  print('Hi ' , name, '!')\r\n  \r\ndef sayhi2(name, greeting):\r\n  \"\"\"\r\n  Hi with custom greeting\r\n  \"\"\"\r\n  print(greeting, name, '!')\r\n<\/pre>\n<p>* Use module<\/p>\n<pre lang=\"python\">\r\nimport sayhi\r\n\r\nsayhi.sayhi('jack')\r\nsayhi.sayhi2('jack', 'Howdi')\r\n<\/pre>\n<p>* Output<\/p>\n<pre lang=\"python\">\r\nHi  jack !\r\nHowdi jack !\r\n<\/pre>\n<span id=\"Namespace\"><h4>Namespace<\/h4><\/span>\n<p>* Prevents name clashes<\/p>\n<pre lang=\"python\">\r\n<\/pre>\n<span id=\"Strings_1\"><h2>Strings<\/h2><\/span>\n<p>* String indexing<\/p>\n<pre lang=\"python\">\r\ns1 = 'apple'\r\ns1[0]\r\n>>>a\r\ns1[3]\r\n>>>l\r\n<\/pre>\n<p>* Negative string indexing<\/p>\n<pre lang=\"python\">\r\ns1 = 'apple'\r\ns1[-1]\r\n>>>e\r\n<\/pre>\n<p>* String slicing<\/p>\n<pre lang=\"python\">\r\n>>> s = 'test string'\r\n>>> s[0:3]\r\n'tes'\r\n>>> s[0:4]\r\n'test'\r\n>>> s[5:11]\r\n'string'\r\n>>> s[:4]\r\n'test'\r\n>>> s[5:]\r\n'string'\r\n>>> s[:]\r\n'test string'\r\n>>> s[-5:]\r\n'tring'\r\n>>> s[-6:]\r\n'string'\r\n>>> s[-11:-6]\r\n<\/pre>\n<p>* Use for-loop to access string characters<\/p>\n<pre lang=\"python\">\r\ndef printchar(str):\r\n  for c in str:\r\n    print(c)\r\n\r\nprintchar('test string')\r\n\r\nt\r\ne\r\ns\r\nt\r\n\r\ns\r\nt\r\nr\r\ni\r\nn\r\ng\r\n<\/pre>\n<span id=\"Characters\"><h3>Characters<\/h3><\/span>\n<p>* Unicode support<br \/>\n- Unicode to char: char(97) is 'a'<br \/>\n- Char to unicode: ord('a') is 97<\/p>\n<span id=\"Standard_String_Functions\"><h3>Standard String Functions<\/h3><\/span>\n<p>\/\/TODO<\/p>\n<pre lang=\"python\">\r\n<\/pre>\n<span id=\"Regular_Expression\"><h3>Regular Expression<\/h3><\/span>\n<pre lang=\"python\">\r\nimport re  # use regular expressions\r\ndef is_done2(s):\r\n  return re.match('done|quit', s) != None\r\n\r\nif is_done2('done') :\r\n  print('done')\r\nelse:\r\n  print('not done')\r\n\r\n>>>\r\ndone\r\n>>>\r\n<\/pre>\n<span id=\"Data_Structure\"><h2>Data Structure<\/h2><\/span>\n<p>* Checking data type: type()<br \/>\n* list<\/p>\n<span id=\"Sequence_Types\"><h3>Sequence Types<\/h3><\/span>\n<p>* An ordered collection of values<br \/>\n* Three built-in sequence types:<br \/>\n- strings<br \/>\n- tuples (like lists but are immutable)<br \/>\n- lists<br \/>\n* For all sequences:<br \/>\n- left end index is 0<br \/>\n- right end index is -1<br \/>\n- can be sliced: <em>seq[beginIdx:endIdx]<\/em><br \/>\n- can be concatenated with + and *.<br \/>\n- length can be determined by <em>len(seq)<\/em> function<br \/>\n- membership can be tested by <em>x in seq<\/em><\/p>\n<span id=\"Tuples\"><h4>Tuples<\/h4><\/span>\n<p>- Items of a tuple are<br \/>\nenclosed in round brackets<br \/>\nseparated by commas<br \/>\n- Tuples are immutables (unlike lists)<\/p>\n<pre lang=\"python\">\r\n# empty tuple\r\n()\r\n\r\n# singleton tuple\r\n(x,)\r\n\r\nitems = (1, 'cat', (2,3))\r\nprint(items)\r\n(1, 'cat', (2, 3))\r\nprint(len(items))\r\n3\r\nprint(items[0])\r\n1\r\nprint(items[-1])\r\n(2, 3)\r\n<\/pre>\n<span id=\"Lists\"><h4>Lists<\/h4><\/span>\n<p>* Like tuples except<br \/>\n- it's <em>mutable<\/em><br \/>\n- Uses [] instead of ()<br \/>\n- Can contain mixed elements<\/p>\n<pre lang=\"python\">\r\nnumbers = [1,2,-3,4]\r\nprint('numbers: ', numbers)\r\nprint('len(numbers): ', len(numbers))\r\nprint('numbers[0]: ', numbers[0])\r\nprint('numbers[2]: ', numbers[2])\r\nprint('numbers[3]: ', numbers[3])\r\nnumbers[0] = 100\r\nprint('now numbers: ', numbers)\r\nprint('now numbers[0]: ', numbers[0])\r\n<\/pre>\n<p>* List functions<\/p>\n<pre lang=\"python\">\r\ns.append(x)\r\ns.count(x)\r\ns.extend(lst)\r\ns.index(x)\r\ns.insert(i, x)\r\ns.pop(i)\r\ns.remove(x)\r\ns.reverse()\r\ns.sort\r\n<\/pre>\n<p>* List comprehensions<\/p>\n<pre lang=\"python\">\r\nprint('[n * n for n in range(1,11)]: ')\r\nprint([n * n for n in range(1,11)])\r\n\r\n[n * n for n in range(1,11)]: \r\n[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]\r\n<\/pre>\n<p>* Examples<\/p>\n<pre lang=\"python\">\r\nlist1 = 'a'\r\nlist2 = 'b'\r\nlist3 = list1 + list2 # ['a', 'b']\r\n\r\nif list1[0] in list3\r\n print 'Found' + list1[0]\r\n<\/pre>\n<span id=\"Dictionaries\"><h4>Dictionaries<\/h4><\/span>\n<p>* To store key:value pairs<br \/>\n* aka maps, hashtables, associative arrays<br \/>\n* Keys must be<br \/>\n- unique<br \/>\n- immutable<br \/>\n* Initialize dictionaries<\/p>\n<pre lang=\"python\">\r\n>>> tel = {'jack': 4098, 'sape': 4139}\r\n>>> tel['guido'] = 4127\r\n>>> tel\r\n{'sape': 4139, 'guido': 4127, 'jack': 4098}\r\n>>> tel['jack']\r\n4098\r\n>>> del tel['sape']\r\n>>> tel['irv'] = 4127\r\n>>> tel\r\n{'guido': 4127, 'irv': 4127, 'jack': 4098}\r\n>>> tel.keys()\r\n['guido', 'irv', 'jack']\r\n>>> 'guido' in tel\r\nTrue\r\n\r\n>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])\r\n{'sape': 4139, 'jack': 4098, 'guido': 4127}\r\n\r\n>>> {x: x**2 for x in (2, 4, 6)}\r\n{2: 4, 4: 16, 6: 36}\r\n\r\n>>> dict(sape=4139, guido=4127, jack=4098)\r\n{'sape': 4139, 'jack': 4098, 'guido': 4127}\r\n<\/pre>\n<p>* Dictionary functions<\/p>\n<pre lang=\"python\">\r\nd.items()\r\nd.keys()\r\nd.values()\r\nd.get(key)\r\nd.popitem()\r\nd.clear()\r\nd.copy()\r\nd.fromkeys(s.t)\r\nd.setdefault(key, v)\r\nd.update(e)\r\n<\/pre>\n<span id=\"Sets\"><h4>Sets<\/h4><\/span>\n<p>* Like list but <strong>no duplicates<\/strong><br \/>\n* Two kinds<br \/>\n- mutable sets<br \/>\n- immutable frozensets<\/p>\n<pre lang=\"python\">\r\nlst = [1,1,1,2,2,3,3]\r\ns = set(lst)\r\nprint(s)\r\n\r\n# we get\r\n{1, 2, 3}\r\n<\/pre>\n<span id=\"IO\"><h2>IO<\/h2><\/span>\n<span id=\"Format_Strings\"><h3>Format Strings<\/h3><\/span>\n<pre lang=\"python\">\r\npi = 3.14159265358979323\r\nprint('pi is %f % pi gives: ', \"pi is %f\" % pi)\r\nprint(\"pi is %0.10f\" % pi)\r\nprint(\"pi is %e\" % pi)\r\n\r\nprint(\"{0} is a {1}\".format('this', 'test'))\r\nprint(\"{pos1} is a {pos2}\".format(pos1 = 'this', pos2 = 'another test'))\r\n<\/pre>\n<span id=\"File_IO\"><h3>File IO<\/h3><\/span>\n<span id=\"Listing_files\"><h4>Listing files<\/h4><\/span>\n<pre lang=\"python\">\r\nimport os\r\n\r\ndef list_cwd():\r\n  \"\"\"\r\n  List files in the current directory\r\n  \"\"\"\r\n  return os.listdir(os.getcwd())\r\n\r\ndef files_cwd():\r\n  \"\"\"\r\n  Return files in the current directory\r\n  as a list\r\n  \"\"\"\r\n  return [p for p in list_cwd() \r\n          if os.path.isfile(p)]\r\n\r\ndef folders_cwd():\r\n  return [p for p in list_cwd() \r\n          if os.path.isdir(p)]\r\n\r\ndef list_py(path = None):\r\n  if path == None:\r\n    path = os.getcwd()\r\n  return [fn for fn in os.listdir(path)\r\n          if os.path.isfile(fn)\r\n          if fn.endswith('.py')]\r\n\r\ndef size_in_bytes(fname):\r\n  return os.stat(fname).st_size\r\n\r\ndef cwd_size_in_bytes():\r\n  total = 0\r\n  for name in files_cwd():\r\n    total = total + size_in_bytes(name)\r\n  return total\r\n\r\ndef cwd_size_in_bytes2( ):\r\n  return sum(size_in_bytes(f) \r\n             for f in files_cwd( ))\r\n             \r\nprint(list_cwd())\r\nprint(files_cwd())\r\nprint(list_py())\r\nprint(size_in_bytes('testfile.py'))\r\nprint(cwd_size_in_bytes())\r\nprint(cwd_size_in_bytes2())\r\n<\/pre>\n<span id=\"File_modes\"><h4>File modes<\/h4><\/span>\n<p>'r': read mode<br \/>\n'w': write mode<br \/>\n'a': append mode<br \/>\n'b': binary mode<br \/>\n't': text mode (default)<br \/>\n'+': open for both read and write<\/p>\n<span id=\"Text_files\"><h4>Text files<\/h4><\/span>\n<p>* Read text file<\/p>\n<pre lang=\"python\">\r\ndef print_file1(fname):\r\n  \"\"\"\r\n  Read file line by line\r\n  \"\"\"\r\n  f = open(fname, 'r')\r\n  for line in f:\r\n    print(line, end = '')\r\n  f.close()\r\n\r\nprint_file1(r'c:\\temp\\test.txt')\r\n\r\ndef print_file2(fname):\r\n  \"\"\"\r\n  Read file as string\r\n  \"\"\"\r\n  f = open(fname, 'r')\r\n  print(f.read())\r\n  f.close()\r\n\r\nprint()\r\nprint_file2(r'c:\\temp\\test.txt')\r\n<\/pre>\n<p>* Write text file<\/p>\n<pre lang=\"python\">\r\ndef write_file1(fname):\r\n  \"\"\"\r\n  Write to a file\r\n  \"\"\"\r\n  if os.path.isfile(fname):\r\n    print(fname, ' already exists.')\r\n  else:\r\n    f = open(fname, 'w')\r\n    f.write('Hello world!\\n')\r\n    f.write('Hello again.\\n')\r\n    f.close()\r\n  \r\nwrite_file1(r'c:\\temp\\textwrite.txt')\r\n<\/pre>\n<span id=\"Binary_File\"><h4>Binary File<\/h4><\/span>\n<p>* Read binary file<\/p>\n<pre lang=\"python\">\r\ndef is_gif(fname):\r\n  \"\"\"\r\n  Check if a file is gif file\r\n  \"\"\"\r\n  f = open(fname, 'br')\r\n  first4 = tuple(f.read(4))\r\n  f.close()\r\n  return first4 == (0x47, 0x49, 0x46, 0x38)\r\n  \r\nprint(is_gif(r'c:\\temp\\textwrite.txt'))\r\n<\/pre>\n<span id=\"Pickling\"><h4>Pickling<\/h4><\/span>\n<p>* aka serialization<\/p>\n<pre lang=\"python\">\r\nimport pickle\r\ndef pickle_file1(infile, outfile):\r\n  inf = open(infile, 'r')\r\n  outf = open(outfile, 'bw')\r\n  pickle.dump(inf.read(), outf)\r\n  inf.close()\r\n  outf.close()\r\n\r\npickle_file1(r'c:\\temp\\test.txt', r'c:\\temp\\testpickle.txt')\r\n\r\ndef unpickle_file1(fname):\r\n  f = open(fname, 'br')\r\n  str = pickle.load(f)\r\n  print(str)\r\n  f.close()\r\n  \r\nunpickle_file1(r'c:\\temp\\testpickle.txt')\r\n<\/pre>\n<span id=\"Read_Web_Page_with_urllib\"><h4>Read Web Page with urllib<\/h4><\/span>\n<pre lang=\"python\">\r\nimport urllib.request\r\n\r\ndef read_webpage1(urlstr):\r\n  resp = urllib.request.urlopen(urlstr)\r\n  return resp.read()\r\n\r\nprint(read_webpage1('http:\/\/www.google.com')[0:50])\r\n\r\nimport webbrowser\r\nwebbrowser.open('http:\/\/www.google.com')\r\n<\/pre>\n<span id=\"Exception_Handling\"><h2>Exception Handling<\/h2><\/span>\n<p>* Raise exception<\/p>\n<pre lang=\"python\">\r\nraise MyTestError('My test exception')\r\n<\/pre>\n<p>* Catch exceptions<\/p>\n<pre lang=\"python\">\r\ndef test_exception():\r\n  try:\r\n    return 'done.'\r\n  except FirstException:\r\n    return 'FirstException'\r\n  except SecondException:\r\n    return 'SecondException'\r\n  except:\r\n    return 'Unknown exceptions'\r\n  finally:\r\n    print('finalized')\r\n\r\nprint(test_exception())\r\n<\/pre>\n<p>* with statement<br \/>\n\/\/TODO<\/p>\n<pre lang=\"python\">\r\n<\/pre>\n<span id=\"OOP\"><h2>OOP<\/h2><\/span>\n<span id=\"Class\"><h3>Class<\/h3><\/span>\n<p>* A method must have self as its first parameter<br \/>\n* Private variables (quasi) use double under scores<\/p>\n<pre lang=\"python\">\r\nclass Person:\r\n  \"\"\"\r\n  Class representing a person\r\n  \"\"\"\r\n  \r\n  # Constructor\r\n  def __init__(self):\r\n    self.name = 'unknown'\r\n    self.__age = 0\r\n  \r\n  def __init__(self, name = 'unknown', age = 0):\r\n    self.__name = name\r\n    self.__age = age\r\n  \r\n  # to string\r\n  def __str__(self):\r\n    return \"Person('%s', '%d')\" % (self.__name, self.__age)\r\n  \r\n  # object official message\r\n  def __repr__(self):\r\n    return str(self)\r\n\r\n  def method1(self):\r\n    return \"method1\"\r\n\r\n  # --------- Getters and Setters    \r\n  @property\r\n  def age(self):\r\n    return self.__age\r\n  \r\n  @age.setter\r\n  def age(self, age):\r\n    if 0 < age < 150:\r\n      self.__age = age\r\n    else:\r\n      raise ValueError('Invalid age.')\r\n    \r\np = Person()\r\nprint(p)\r\n\r\np2 = Person('John', 25)\r\nprint(p2)\r\nprint(p2.age)\r\n\r\np2.age = 95\r\nprint(p2.age)\r\n\r\np2._Person__age = 105\r\nprint(p2.age)\r\n\r\n#p2.age = 200\r\n#print(p2.age)\r\n<\/pre>\n<span id=\"Inheritance\"><h3>Inheritance<\/h3><\/span>\n<pre lang=\"python\">\r\n# --------- Programmer inherits Person\r\nclass Programmer(Person):\r\n  # Override object official message\r\n  def __repr__(self):\r\n    return \"Programmer: %s\" % str(self)\r\n\r\n  # Override method1\r\n  def method1(self):\r\n    return \"Programmer: method1\"\r\n\r\nprogrammer1 = Programmer('Jane', 30)\r\nprint(programmer1)\r\nprint(programmer1.method1())\r\n<\/pre>\n<span id=\"Polymorphism\"><h3>Polymorphism<\/h3><\/span>\n<pre lang=\"python\">\r\n# Define a base Player class\r\nclass Player:\r\n  def __init__(self, name):\r\n    self._name = name\r\n    self._score = 0\r\n\r\n  def reset_score(self):\r\n    self._score = 0\r\n\r\n  def incr_score(self):\r\n    self._score = self._score + 1\r\n\r\n  def get_name(self):\r\n    return self._name\r\n\r\n  def __str__(self):\r\n    return \"name = '%s', score = %s\" % (self._name, self._score)\r\n\r\n  def __repr__(self):\r\n    return 'Player(%s)' % str(self)\r\n\r\n# Define a human player by extending Player class\r\nclass Human(Player):\r\n  def __repr__(self):\r\n    return 'Human(%s)' % str(self)\r\n  \r\n  # Define how human selects a move\r\n  def get_move(self):\r\n    while True:\r\n      try:\r\n        n = int(input('%s move (1 - 10): ' % self.get_name()))\r\n        if 1 <= n <= 10:\r\n          return n\r\n        else:\r\n          print('try again!')\r\n      except:\r\n        print('try again.')\r\n\r\n# Define a computer player by extending Player class\r\nimport random\r\nclass Computer(Player):\r\n  def __repr__(self):\r\n    return 'Computer(%s) % str(self)'\r\n  \r\n  # Define how computer makes a move\r\n  def get_move(self):\r\n    return random.randint(1, 10)\r\n\r\n# Define a game function\r\n# The game does not know if p1 and p2 are human or computer,\r\n# it invokes different moves depending on \r\n# if p1 and p2 are human or computer (polymorphism)\r\ndef play_undercut(p1, p2):\r\n  p1.reset_score()\r\n  p2.reset_score()\r\n  m1 = p1.get_move()\r\n  m2 = p2.get_move()\r\n  \r\n  print(\"%s move: %s\" % (p1.get_name(), m1))\r\n  print(\"%s move: %s\" % (p2.get_name(), m2))\r\n  \r\n  if m1 == m2 - 1:\r\n    p1.incr_score()\r\n    print(p1, '\\n\\r', p2, '\\n\\r%s wins!' % p1.get_name())\r\n  elif m2 == m1 - 1:\r\n    p2.incr_score()\r\n    print(p1, '\\n\\r', p2, '\\n\\r%s wins!' % p2.get_name())\r\n  else:\r\n    print(p1, '\\n\\r', p2, '\\n\\rdraw: nobody win\\n')\r\n\r\n  print('done\\r\\n')\r\n  \r\n# Start game\r\nc = Computer('Hal')\r\nh = Human('Jane')\r\nplay_undercut(c,h)\r\n\r\n# Computer vs computer\r\nc1 = Computer('Hal')\r\nc2 = Computer('hal2')\r\nplay_undercut(c1, c2)\r\n\r\n# Human vs Human\r\nh1 = Human('John')\r\nh2 = Human('Jane')\r\nplay_undercut(h1, h2)\r\n<\/pre>\n<span id=\"References\"><h2>References<\/h2><\/span>\n<p>* Python: Visual QuickStart Guide, Second Edition By: Toby Donaldson<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Overview * Started by Guido van Rossum * Named after Morty Python comedy troupe * Supports OOP (No interface support) * No curly brackets, colon sign and indentation are used instead * Statement indentations are significant in Python. &#8211; Don&#8217;t &hellip; <a href=\"https:\/\/jianmingli.com\/wp\/?p=2104\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_exactmetrics_skip_tracking":false,"_exactmetrics_sitenote_active":false,"_exactmetrics_sitenote_note":"","_exactmetrics_sitenote_category":0,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2}},"categories":[94],"tags":[],"class_list":["post-2104","post","type-post","status-publish","format-standard","hentry","category-python"],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack_shortlink":"https:\/\/wp.me\/s8cRUO-python","_links":{"self":[{"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/posts\/2104","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2104"}],"version-history":[{"count":17,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/posts\/2104\/revisions"}],"predecessor-version":[{"id":10764,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=\/wp\/v2\/posts\/2104\/revisions\/10764"}],"wp:attachment":[{"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2104"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2104"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jianmingli.com\/wp\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2104"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}