Browse Source

Adding remaining chapters

Swaroop C H 12 years ago
parent
commit
cefd54141c
6 changed files with 533 additions and 0 deletions
  1. 224 0
      17-more.pd
  2. 141 0
      18-what-next.pd
  3. 55 0
      19-appendix-floss.pd
  4. 29 0
      20-appendix-about.pd
  5. 59 0
      21-revision-history.pd
  6. 25 0
      fabfile.py

+ 224 - 0
17-more.pd

@@ -0,0 +1,224 @@
+# More
+
+So far we have covered a majority of the various aspects of Python that you will use. In this chapter, we will cover some more aspects that will make our knowledge of Python more well-rounded.
+
+## Passing tuples around 
+
+Ever wished you could return two different values from a function? You can. All you have to do is use a tuple.
+
+~~~
+>>> def get_error_details():
+...     return (2, 'second error details')
+...
+>>> errnum, errstr = get_error_details()
+>>> errnum
+2
+>>> errstr
+'second error details'
+~~~
+
+Notice that the usage of `a, b = <some expression>` interprets the result of the expression as a tuple with two values.
+
+If you want to interpret the results as `(a, <everything else>)`, then you just need to star it just like you would in function parameters:
+
+~~~
+>>> a, *b = [1, 2, 3, 4]
+>>> a
+1
+>>> b
+[2, 3, 4]
+~~~
+
+This also means the fastest way to swap two variables in Python is:
+
+~~~
+>>> a = 5; b = 8
+>>> a, b = b, a
+>>> a, b
+(8, 5)
+~~~
+
+## Special Methods 
+
+There are certain methods such as the `__init__` and `__del__` methods which have special significance in classes.
+
+Special methods are used to mimic certain behaviors of built-in types. For example, if you want to use the `x[key]` indexing operation for your class (just like you use it for lists and tuples), then all you have to do is implement the `__getitem__()` method and your job is done. If you think about it, this is what Python does for the `list` class itself!
+
+Some useful special methods are listed in the following table. If you want to know about all the special methods, [see the manual](http://docs.python.org/3.0/reference/datamodel.html#special-method-names).
+
+`__init__(self, ...)`
+
+:   This method is called just before the newly created object is returned for usage.
+
+`__del__(self)`
+
+:   Called just before the object is destroyed
+
+`__str__(self)`
+
+:   Called when we use the `print` function or when `str()`is used.
+
+`__lt__(self, other)`
+
+:   Called when the *less than* operator (<) is used. Similarly, there are special methods for all the operators (+, >, etc.)
+
+`__getitem__(self, key)`
+
+:   Called when `x[key]` indexing operation is used.
+
+`__len__(self)`
+
+:   Called when the built-in `len()` function is used for the sequence object.
+
+## Single Statement Blocks 
+
+We have seen that each block of statements is set apart from the rest by its own indentation level. Well, there is one caveat. If your block of statements contains only one single statement, then you can specify it on the same line of, say, a conditional statement or looping statement. The following example should make this clear: 
+
+~~~
+>>> flag = True
+>>> if flag: print('Yes')
+Yes
+~~~
+
+Notice that the single statement is used in-place and not as a separate block.  Although, you can use this for making your program *smaller*, I strongly recommend avoiding this short-cut method, except for error checking, mainly because it will be much easier to add an extra statement if you are using proper indentation.
+
+## Lambda Forms 
+
+A `lambda` statement is used to create new function objects and then return them at runtime.
+
+~~~python
+#!/usr/bin/python
+# Filename: lambda.py
+
+def make_repeater(n):
+    return lambda s: s * n
+
+twice = make_repeater(2)
+
+print(twice('word'))
+print(twice(5))
+~~~
+
+Output:
+
+~~~
+$ python lambda.py
+wordword
+10
+~~~
+
+How It Works:
+
+Here, we use a function `make_repeater` to create new function objects at runtime and return it. A `lambda` statement is used to create the function object. Essentially, the `lambda` takes a parameter followed by a single expression only which becomes the body of the function and the value of this expression is returned by the new function. Note that even a `print` statement cannot be used inside a lambda form, only expressions.
+
+**TODO** Can we do a `list.sort()` by providing a key function created using `lambda`?
+
+~~~python
+points = [ { 'x' : 2, 'y' : 3 }, { 'x' : 4, 'y' : 1 } ]
+# points.sort(key=lambda a : a['x'])
+~~~
+
+## List Comprehension 
+
+List comprehensions are used to derive a new list from an existing list. Suppose you have a list of numbers and you want to get a corresponding list with all the numbers multiplied by 2 only when the number itself is greater than 2. List comprehensions are ideal for such situations.
+
+~~~python
+#!/usr/bin/python
+# Filename: list_comprehension.py
+
+listone = [2, 3, 4]
+listtwo = [2*i for i in listone if i > 2]
+print(listtwo)
+~~~
+
+Output:
+
+~~~
+$ python list_comprehension.py
+[6, 8]
+~~~
+
+How It Works:
+
+Here, we derive a new list by specifying the manipulation to be done (`2*i`) when some condition is satisfied (`if i > 2`). Note that the original list remains unmodified. 
+
+The advantage of using list comprehensions is that it reduces the amount of boilerplate code required when we use loops to process each element of a list and store it in a new list.
+
+## Receiving Tuples and Dictionaries in Functions 
+
+There is a special way of receiving parameters to a function as a tuple or a dictionary using the * or ** prefix respectively. This is useful when taking variable number of arguments in the function.
+
+~~~
+>>> def powersum(power, *args):
+...     '''Return the sum of each argument raised to        specified power.'''
+...     total = 0
+...     for i in args:
+...         total += pow(i, power)
+...     return total
+...
+>>> powersum(2, 3, 4)
+25
+
+>>> powersum(2, 10)
+100
+~~~
+
+Because we have a `*` prefix on the `args` variable, all extra arguments passed to the function are stored in `args` as a tuple.  If a ** prefix had been used instead, the extra parameters would be considered to be key/value pairs of a dictionary.
+
+## exec and eval 
+
+The `exec` function is used to execute Python statements which are stored in a string or file, as opposed to written in the program itself. For example, we can generate a string containing Python code at runtime and then execute these statements using the `exec` statement:
+
+~~~
+>>> exec('print("Hello World")')
+Hello World
+~~~
+
+Similarly, the `eval` function is used to evaluate valid Python expressions which are stored in a string. A simple example is shown below.
+
+~~~
+>>> eval('2*3')
+6
+~~~
+
+## The assert statement 
+
+The `assert` statement is used to assert that something is true. For example, if you are very sure that you will have at least one element in a list you are using and want to check this, and raise an error if it is not true, then `assert` statement is ideal in this situation. When the assert statement fails, an `AssertionError` is raised.
+
+~~~
+>>> mylist = ['item']
+>>> assert len(mylist) >= 1
+>>> mylist.pop()
+'item'
+>>> mylist
+[]
+>>> assert len(mylist) >= 1
+Traceback (most recent call last):
+File "<stdin>", line 1, in <module>
+AssertionError
+~~~
+
+The `assert` statement should be used judiciously. Most of the time, it is better to catch exceptions, either handle the problem or display an error message to the user and then quit.
+
+## The repr function 
+
+The `repr` function is used to obtain a canonical string representation of the object. The interesting part is that you will have `eval(repr(object)) == object` most of the time.
+
+~~~
+>>> i = []
+>>> i.append('item')
+>>> repr(i)
+"['item']"
+>>> eval(repr(i))
+['item']
+>>> eval(repr(i)) == i
+True
+~~~
+
+Basically, the `repr` function is used to obtain a printable representation of the object. You can control what your classes return for the `repr` function by defining the `__repr__` method in your class.
+
+## Summary 
+
+We have covered some more features of Python in this chapter and yet we haven't covered all the features of Python. However, at this stage, we have covered most of what you are ever going to use in practice. This is sufficient for you to get started with whatever programs you are going to create.
+
+Next, we will discuss how to explore Python further.

File diff suppressed because it is too large
+ 141 - 0
18-what-next.pd


File diff suppressed because it is too large
+ 55 - 0
19-appendix-floss.pd


+ 29 - 0
20-appendix-about.pd

@@ -0,0 +1,29 @@
+# Colophon 
+
+Almost all of the software that I have used in the creation of this book are [FLOSS](#floss).
+
+## Birth of the Book 
+
+In the first draft of this book, I had used Red Hat 9.0 Linux as the foundation of my setup and in the sixth draft, I used Fedora Core 3 Linux as the basis of my setup.
+
+Initially, I was using KWord to write the book (as explained in the [history lesson](#history-lesson) in the preface).
+
+## Teenage Years 
+
+Later, I switched to DocBook XML using Kate but I found it too tedious. So, I switched to OpenOffice which was just excellent with the level of control it provided for formatting as well as the PDF generation, but it produced very sloppy HTML from the document.
+
+Finally, I discovered XEmacs and I rewrote the book from scratch in DocBook XML (again) after I decided that this format was the long term solution.
+
+In the sixth draft, I decided to use Quanta+ to do all the editing. The standard XSL stylesheets that came with Fedora Core 3 Linux were being used. However, I had written a CSS document to give color and style to the HTML pages. I had also written a crude lexical analyzer, in Python of course, which automatically provides syntax highlighting to all the program listings.
+
+For this seventh draft, I'm using [MediaWiki](http://www.mediawiki.org ) as the basis of my [setup](http://www.swaroopch.com/notes/). Now I edit everything online and the readers can directly read/edit/discuss within the wiki website.
+
+I used Vim for editing thanks to the [ViewSourceWith extension for Firefox](https://addons.mozilla.org/en-US/firefox/addon/394) that integrates with Vim.
+
+## Now
+
+Using Vim, Pandoc, and Mac OS X.
+
+## About The Author 
+
+<http://www.swaroopch.com/about/>

+ 59 - 0
21-revision-history.pd

@@ -0,0 +1,59 @@
+# Revision History
+
+- 2.0
+    - 20 Oct 2012
+    - Rewriting using [Pandoc](http://johnmacfarlane.net/pandoc/README.html), thanks to my wife!
+    - Simplifying text, removing non-essential sections such as `nonlocal` and metaclasses
+- 1.90 
+    - 04 Sep 2008 and still in progress 
+    - Revival after a gap of 3.5 years! 
+    - Rewriting for Python 3.0
+    - Rewrite using [MediaWiki](http://www.mediawiki.org) (again) 
+- 1.20 
+    - 13 Jan 2005
+    - Complete rewrite using [Quanta+](https://en.wikipedia.org/wiki/Quanta_Plus) on [Fedora](http://fedoraproject.org/) Core 3 with lot of corrections and updates. Many new examples. Rewrote my DocBook setup from scratch. 
+- 1.15 
+    - 28 Mar 2004
+    - Minor revisions 
+- 1.12 
+    - 16 Mar 2004
+    - Additions and corrections. 
+- 1.10 
+    - 09 Mar 2004
+    - More typo corrections, thanks to many enthusiastic and helpful readers. 
+- 1.00 
+    - 08 Mar 2004
+    - After tremendous feedback and suggestions from readers, I have made significant revisions to the content along with typo corrections. 
+- 0.99 
+    - 22 Feb 2004
+    - Added a new chapter on modules. Added details about variable number of arguments in functions. 
+- 0.98 
+    - 16 Feb 2004
+    - Wrote a Python script and CSS stylesheet to improve XHTML output, including a crude-yet-functional lexical analyzer for automatic VIM-like syntax highlighting of the program listings. 
+- 0.97 
+    - 13 Feb 2004
+    - Another completely rewritten draft, in DocBook XML (again). Book has improved a lot - it is more coherent and readable. 
+- 0.93 
+    - 25 Jan 2004
+    - Added IDLE talk and more Windows-specific stuff 
+- 0.92 
+    - 05 Jan 2004
+    - Changes to few examples. 
+- 0.91 
+    - 30 Dec 2003
+    - Corrected typos. Improvised many topics. 
+- 0.90 
+    - 18 Dec 2003
+    - Added 2 more chapters. [OpenOffice](https://en.wikipedia.org/wiki/OpenOffice) format with revisions. 
+- 0.60 
+    - 21 Nov 2003
+    - Fully rewritten and expanded. 
+- 0.20 
+    - 20 Nov 2003
+    - Corrected some typos and errors. 
+- 0.15 
+    - 20 Nov 2003
+    - Converted to [DocBook XML](https://en.wikipedia.org/wiki/DocBook). 
+- 0.10 
+    - 14 Nov 2003
+    - Initial draft using [KWord](https://en.wikipedia.org/wiki/Kword).

+ 25 - 0
fabfile.py

@@ -92,6 +92,31 @@ MARKDOWN_FILES = [
         'slug': "python_en-standard_library",
         'title': "Python : Standard Library",
     },
+    {
+        'file': '17-more.pd',
+        'slug': "python_en-more",
+        'title': "Python : More",
+    },
+    {
+        'file': '18-what-next.pd',
+        'slug': "python_en-what_next",
+        'title': "Python : What Next",
+    },
+    {
+        'file': '19-appendix-floss.pd',
+        'slug': "python_en-appendix_floss",
+        'title': "Python : Appendix : FLOSS",
+    },
+    {
+        'file': '20-appendix-about.pd',
+        'slug': "python_en-appendix_about",
+        'title': "Python : Appendix : About",
+    },
+    {
+        'file': '21-revision-history.pd',
+        'slug': "python_en-appendix_revision_history",
+        'title': "Python : Appendix : Revision History",
+    },
 ]