Selaa lähdekoodia

Updates for Python 3

Swaroop C H 12 vuotta sitten
vanhempi
commit
f8d4814253
14 muutettua tiedostoa jossa 183 lisäystä ja 349 poistoa
  1. 13 13
      07-operators-expressions.pd
  2. 19 32
      08-control-flow.pd
  3. 21 51
      09-functions.pd
  4. 17 49
      10-modules.pd
  5. 12 30
      11-data-structures.pd
  6. 16 20
      12-problem-solving.pd
  7. 10 24
      13-oop.pd
  8. 9 16
      14-io.pd
  9. 14 18
      15-exceptions.pd
  10. 22 20
      16-standard-library.pd
  11. 19 47
      17-more.pd
  12. 9 27
      18-what-next.pd
  13. 1 1
      20-appendix-about.pd
  14. 1 1
      21-revision-history.pd

+ 13 - 13
07-operators-expressions.pd

@@ -65,7 +65,7 @@ Note that you can evaluate the expressions given in the examples using the inter
 :   Shifts the bits of the number to the left by the number of bits specified. (Each number is represented in memory by bits or binary digits i.e. 0 and 1)
 
     `2 << 2` gives `8`. `2` is represented by `10` in bits.
-    
+
     Left shifting by 2 bits gives `1000` which represents the decimal `8`.
 
 `>>` (right shift)
@@ -73,7 +73,7 @@ Note that you can evaluate the expressions given in the examples using the inter
 :   Shifts the bits of the number to the right by the number of bits specified.
 
     `11 >> 1` gives `5`.
-    
+
     `11` is represented in bits by `1011` which when right shifted by 1 bit
     gives `101`which is the decimal `5`.
 
@@ -167,15 +167,18 @@ It is common to run a math operation on a variable and then assign the result of
 
 You can write:
 
-
-    a = 2; a = a * 3
+~~~python
+a = 2
+a = a * 3
+~~~
 
 
 as:
 
-
-    a = 2; a *= 3
-
+~~~python
+a = 2
+a *= 3
+~~~
 
 Notice that `var = var operation expression` becomes `var operation= expression`.
 
@@ -185,7 +188,7 @@ If you had an expression such as `2 + 3 * 4`, is the addition done first or the
 
 The following table gives the precedence table for Python, from the lowest precedence (least binding) to the highest precedence (most binding). This means that in a given expression, Python will first evaluate the operators and expressions lower in the table before the ones listed higher in the table.
 
-The following table, taken from the [Python reference manual](http://docs.python.org/3.0/reference/expressions.html#evaluation-order), is provided for the sake of completeness. It is far better to use parentheses to group operators and operands appropriately in order to explicitly specify the precedence. This makes the program more readable. See [Changing the Order of Evaluation](#changing-the-order-of-evaluation) below for details.
+The following table, taken from the [Python reference manual](http://docs.python.org/py3k/reference/expressions.html#summary), is provided for the sake of completeness. It is far better to use parentheses to group operators and operands appropriately in order to explicitly specify the precedence. This makes the program more readable. See [Changing the Order of Evaluation](#changing-the-order-of-evaluation) below for details.
 
 `lambda`
 
@@ -295,12 +298,9 @@ Operators are usually associated from left to right. This means that operators w
 
 ## Expressions
 
-Example:
+Example (save as `expression.py`):
 
 ~~~python
-#!/usr/bin/python
- Filename: expression.py
-
 length = 5
 breadth = 2
 
@@ -312,7 +312,7 @@ print('Perimeter is', 2 * (length + breadth))
 Output:
 
 ~~~
-$ python expression.py
+$ python3 expression.py
 Area is 10
 Perimeter is 14
 ~~~

+ 19 - 32
08-control-flow.pd

@@ -8,12 +8,9 @@ As you might have guessed, this is achieved using control flow statements. There
 
 The `if` statement is used to check a condition: *if* the condition is true, we run a block of statements (called the *if-block*), *else* we process another block of statements (called the *else-block*). The *else* clause is optional.
 
-Example:
-
-~~~ python
-#!/usr/bin/python
-# Filename: if.py
+Example (save as `if.py`):
 
+~~~python
 number = 23
 guess = int(input('Enter an integer : '))
 
@@ -34,17 +31,17 @@ print('Done')
 Output:
 
 ~~~
-$ python if.py
+$ python3 if.py
 Enter an integer : 50
 No, it is a little lower than that
 Done
 
-$ python if.py
+$ python3 if.py
 Enter an integer : 22
 No, it is a little higher than that
 Done
 
-$ python if.py
+$ python3 if.py
 Enter an integer : 23
 Congratulations, you guessed it.
 (but you do not win any prizes!)
@@ -86,12 +83,9 @@ Note for C/C++ Programmers
 
 The `while` statement allows you to repeatedly execute a block of statements as long as a condition is true. A `while` statement is an example of what is called a *looping* statement. A `while` statement can have an optional `else` clause.
 
-Example:
+Example (save as `while.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: while.py
-
 number = 23
 running = True
 
@@ -115,7 +109,7 @@ print('Done')
 Output:
 
 ~~~
-$ python while.py
+$ python3 while.py
 Enter an integer : 50
 No, it is a little lower than that.
 Enter an integer : 22
@@ -144,12 +138,9 @@ Note for C/C++ Programmers
 
 The `for..in` statement is another looping statement which *iterates* over a sequence of objects i.e. go through each item in a sequence. We will see more about [sequences](#sequence) in detail in later chapters. What you need to know right now is that a sequence is just an ordered collection of items.
 
-Example:
+Example (save as `for.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: for.py
-
 for i in range(1, 5):
     print(i)
 else:
@@ -159,7 +150,7 @@ else:
 Output:
 
 ~~~
-$ python for.py
+$ python3 for.py
 1
 2
 3
@@ -193,12 +184,9 @@ The `break` statement is used to *break* out of a loop statement i.e. stop the e
 
 An important note is that if you *break* out of a `for`or `while` loop, any corresponding loop `else` block is **not** executed.
 
-Example:
+Example (save as `break.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: break.py
-
 while True:
     s = input('Enter something : ')
     if s == 'quit':
@@ -210,7 +198,7 @@ print('Done')
 Output:
 
 ~~~
-$ python break.py
+$ python3 break.py
 Enter something : Programming is fun
 Length of the string is 18
 Enter something : When the work is done
@@ -235,21 +223,20 @@ Remember that the `break` statement can be used with the `for` loop as well.
 
 The input I have used here is a mini poem I have written called *Swaroop's Poetic Python*:
 
-    Programming is fun
-    When the work is done
-    if you wanna make your work also fun:
-        use Python!
+~~~
+Programming is fun
+When the work is done
+if you wanna make your work also fun:
+    use Python!
+~~~
 
 ## The continue Statement 
 
 The `continue` statement is used to tell Python to skip the rest of the statements in the current loop block and to *continue* to the next iteration of the loop.
 
-Example:
+Example (save as `continue.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: continue.py
-
 while True:
     s = input('Enter something : ')
     if s == 'quit':
@@ -264,7 +251,7 @@ while True:
 Output:
 
 ~~~
-$ python continue.py
+$ python3 continue.py
 Enter something : a
 Too small
 Enter something : 12

+ 21 - 51
09-functions.pd

@@ -6,12 +6,9 @@ The function concept is probably *the* most important building block of any non-
 
 Functions are defined using the `def` keyword. After this keyword comes an *identifier* name for the function, followed by a pair of parentheses which may enclose some names of variables, and by the final colon that ends the line. Next follows the block of statements that are part of this function. An example will show that this is actually very simple:
 
-Example:
+Example (save as `function1.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: function1.py
-
 def sayHello():
     print('Hello World!') # block belonging to the function
 # End of function
@@ -23,7 +20,7 @@ sayHello() # call the function again
 Output:
 
 ~~~
-$ python function1.py
+$ python3 function1.py
 Hello World!
 Hello World!
 ~~~
@@ -40,12 +37,9 @@ A function can take parameters, which are values you supply to the function so t
 
 Parameters are specified within the pair of parentheses in the function definition, separated by commas. When we call the function, we supply the values in the same way.  Note the terminology used - the names given in the function definition are called *parameters* whereas the values you supply in the function call are called *arguments*.
 
-Example:
+Example (save as `func_param.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: func_param.py
-
 def printMax(a, b):
     if a > b:
         print(a, 'is maximum')
@@ -65,7 +59,7 @@ printMax(x, y) # give variables as arguments
 Output:
 
 ~~~
-$ python func_param.py
+$ python3 func_param.py
 4 is maximum
 7 is maximum
 ~~~
@@ -80,12 +74,9 @@ The first time we call the function `printMax`, we directly supply the numbers a
 
 When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function - i.e. variable names are *local* to the function. This is called the *scope* of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name.
 
-Example:
+Example (save as `func_local.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: func_local.py
-
 x = 50
 
 def func(x):
@@ -100,7 +91,7 @@ print('x is still', x)
 Output:
 
 ~~~
-$ python func_local.py
+$ python3 func_local.py
 x is 50
 Changed local x to 2
 x is still 50
@@ -120,12 +111,9 @@ If you want to assign a value to a name defined at the top level of the program
 
 You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). However, this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable's definition is. Using the `global` statement makes it amply clear that the variable is defined in an outermost block.
 
-Example:
+Example (save as `func_global.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: func_global.py
-
 x = 50
 
 def func():
@@ -142,7 +130,7 @@ print('Value of x is', x)
 Output:
 
 ~~~
-$ python func_global.py
+$ python3 func_global.py
 x is 50
 Changed global x to 2
 Value of x is 2
@@ -160,12 +148,9 @@ For some functions, you may want to make some parameters *optional* and use defa
 
 Note that the default argument value should be a constant. More precisely, the default argument value should be immutable - this is explained in detail in later chapters. For now, just remember this.
 
-Example:
+Example (save as `func_default.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: func_default.py
-
 def say(message, times = 1):
     print(message * times)
 
@@ -176,7 +161,7 @@ say('World', 5)
 Output:
 
 ~~~
-$ python func_default.py
+$ python3 func_default.py
 Hello
 WorldWorldWorldWorldWorld
 ~~~
@@ -199,12 +184,9 @@ If you have some functions with many parameters and you want to specify only som
 
 There are two *advantages* - one, using the function is easier since we do not need to worry about the order of the arguments. Two, we can give values to only those parameters to which we want to, provided that the other parameters have default argument values.
 
-Example:
+Example (save as `func_key.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: func_key.py
-
 def func(a, b=5, c=10):
     print('a is', a, 'and b is', b, 'and c is', c)
 
@@ -216,7 +198,7 @@ func(c=50, a=100)
 Output:
 
 ~~~
-$ python func_key.py
+$ python3 func_key.py
 a is 3 and b is 7 and c is 10
 a is 25 and b is 5 and c is 24
 a is 100 and b is 5 and c is 50
@@ -234,12 +216,9 @@ In the third usage `func(c=50, a=100)`, we use keyword arguments for all specifi
 
 ## VarArgs parameters
 
-Sometimes you might want to define a function that can take *any* number of parameters, this can be achieved by using the stars:
+Sometimes you might want to define a function that can take *any* number of parameters, this can be achieved by using the stars (save as `total.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: total.py
-
 def total(initial=5, *numbers, **keywords):
     count = initial
     for number in numbers:
@@ -254,7 +233,7 @@ print(total(10, 1, 2, 3, vegetables=50, fruits=100))
 Output:
 
 ~~~
-$ python total.py
+$ python3 total.py
 166
 ~~~
 
@@ -268,12 +247,9 @@ We will explore tuples and dictionaries in a [later chapter](#data-structures).
 
 ## Keyword-only Parameters 
 
-If we want to specify certain keyword parameters to be available as keyword-only and *not* as positional arguments, they can be declared after a starred parameter:
+If we want to specify certain keyword parameters to be available as keyword-only and *not* as positional arguments, they can be declared after a starred parameter (save as `keyword_only.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: keyword_only.py
-
 def total(initial=5, *numbers, extra_number):
     count = initial
     for number in numbers:
@@ -289,7 +265,7 @@ total(10, 1, 2, 3)
 Output:
 
 ~~~
-$ python keyword_only.py
+$ python3 keyword_only.py
 66
 Traceback (most recent call last):
   File "keyword_only.py", line 12, in <module>
@@ -309,12 +285,9 @@ If you want to have keyword-only arguments but have no need for a starred parame
 
 The `return` statement is used to *return* from a function i.e. break out of the function. We can optionally *return a value* from the function as well.
 
-Example:
+Example (save as `func_return.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: func_return.py
-
 def maximum(x, y):
     if x > y:
         return x
@@ -329,13 +302,13 @@ print(maximum(2, 3))
 Output:
 
 ~~~
-$ python func_return.py
+$ python3 func_return.py
 3
 ~~~
 
 How It Works:
 
-The `maximum` function returns the maximum of the parameters, in this case the numbers supplied to the function. It uses a simple `if..else`	 statement to find the greater value and then *returns* that value.
+The `maximum` function returns the maximum of the parameters, in this case the numbers supplied to the function. It uses a simple `if..else` statement to find the greater value and then *returns* that value.
 
 Note that a `return` statement without a value is equivalent to `return None`. `None` is a special type in Python that represents nothingness. For example, it is used to indicate that a variable has no value if it has a value of `None`.
 
@@ -356,12 +329,9 @@ Note
 
 Python has a nifty feature called *documentation strings*, usually referred to by its shorter name *docstrings*. DocStrings are an important tool that you should make use of since it helps to document the program better and makes it easier to understand. Amazingly, we can even get the docstring back from, say a function, when the program is actually running!
 
-Example:
+Example (save as `func_doc.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: func_doc.py
-
 def printMax(x, y):
     '''Prints the maximum of two numbers.
 
@@ -381,7 +351,7 @@ print(printMax.__doc__)
 Output:
 
 ~~~
-$ python func_doc.py
+$ python3 func_doc.py
 5 is maximum
 Prints the maximum of two numbers.
 

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 17 - 49
10-modules.pd


+ 12 - 30
11-data-structures.pd

@@ -20,12 +20,9 @@ A class can also have **methods** i.e. functions defined for use with respect to
 
 A class can also have **fields** which are nothing but variables defined for use with respect to that class only. You can use these variables/names only when you have an object of that class. Fields are also accessed by the dotted notation, for example, `mylist.field`.
 
-Example:
+Example (save as `using_list.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: using_list.py
-
 # This is my shopping list
 shoplist = ['apple', 'mango', 'carrot', 'banana']
 
@@ -53,7 +50,7 @@ print('My shopping list is now', shoplist)
 Output:
 
 ~~~
-$ python using_list.py
+$ python3 using_list.py
 I have 4 items to purchase.
 These items are: apple mango carrot banana
 I also have to buy rice.
@@ -89,12 +86,9 @@ Tuples are defined by specifying items separated by commas within an optional pa
 
 Tuples are usually used in cases where a statement or a user-defined function can safely assume that the collection of values i.e. the tuple of values used will not change.
 
-Example:
+Example (save as `using_tuple.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: using_tuple.py
-
 zoo = ('python', 'elephant', 'penguin') # remember the parentheses are optional
 print('Number of animals in the zoo is', len(zoo))
 
@@ -109,7 +103,7 @@ print('Number of animals in the new zoo is', len(new_zoo)-1+len(new_zoo[2]))
 Output:
 
 ~~~
-$ python using_tuple.py
+$ python3 using_tuple.py
 Number of animals in the zoo is 3
 Number of cages in the new zoo is 3
 All animals in new zoo are ('monkey', 'camel', ('python', 'elephant', 'penguin'))
@@ -150,12 +144,9 @@ Remember that key-value pairs in a dictionary are not ordered in any manner. If
 
 The dictionaries that you will be using are instances/objects of the `dict` class.
 
-Example:
+Example (save as `using_dict.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: using_dict.py
-
 # 'ab' is short for 'a'ddress'b'ook
 
 ab = {  'Swaroop'   : 'swaroop@swaroopch.com',
@@ -184,7 +175,7 @@ if 'Guido' in ab:
 Output:
 
 ~~~
-$ python using_dict.py
+$ python3 using_dict.py
 Swaroop's address is swaroop@swaroopch.com
 
 There are 3 contacts in the address-book
@@ -222,12 +213,9 @@ The major features are **membership tests**, (i.e. the `in` and `not in` express
 
 The three types of sequences mentioned above - lists, tuples and strings, also have a **slicing** operation which allows us to retrieve a slice of the sequence i.e. a part of the sequence.
 
-Example:
+Example (save as `seq.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: seq.py
-
 shoplist = ['apple', 'mango', 'carrot', 'banana']
 name = 'swaroop'
 
@@ -256,7 +244,7 @@ print('characters start to end is', name[:])
 Output:
 
 ~~~
-$ python seq.py
+$ python3 seq.py
 Item 0 is apple
 Item 1 is mango
 Item 2 is carrot
@@ -337,12 +325,9 @@ When you create an object and assign it to a variable, the variable only *refers
 
 Generally, you don't need to be worried about this, but there is a subtle effect due to references which you need to be aware of:
 
-Example:
+Example (save as `reference.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: reference.py
-
 print('Simple Assignment')
 shoplist = ['apple', 'mango', 'carrot', 'banana']
 mylist = shoplist # mylist is just another name pointing to the same object!
@@ -366,7 +351,7 @@ print('mylist is', mylist)
 Output:
 
 ~~~
-$ python reference.py
+$ python3 reference.py
 Simple Assignment
 shoplist is ['mango', 'carrot', 'banana']
 mylist is ['mango', 'carrot', 'banana']
@@ -391,12 +376,9 @@ We have already discussed strings in detail earlier. What more can there be to k
 
 The strings that you use in program are all objects of the class `str`.  Some useful methods of this class are demonstrated in the next example. For a complete list of such methods, see `help(str)`.
 
-Example:
+Example (save as `str_methods.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: str_methods.py
-
 name = 'Swaroop' # This is a string object
 
 if name.startswith('Swa'):
@@ -417,7 +399,7 @@ print(delimiter.join(mylist))
 Output:
 
 ~~~
-$ python str_methods.py
+$ python3 str_methods.py
 Yes, the string starts with "Swa"
 Yes, it contains the string "a"
 Yes, it contains the string "war"

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 16 - 20
12-problem-solving.pd


+ 10 - 24
13-oop.pd

@@ -31,12 +31,9 @@ This also means that if you have a method which takes no arguments, then you sti
 
 ## Classes 
 
-The simplest class possible is shown in the following example.
+The simplest class possible is shown in the following example (save as `simplestclass.py`).
 
 ~~~python
-#!/usr/bin/python
-# Filename: simplestclass.py
-
 class Person:
     pass # An empty block
 
@@ -47,7 +44,7 @@ print(p)
 Output:
 
 ~~~
-$ python simplestclass.py
+$ python3 simplestclass.py
 <__main__.Person object at 0x019F85F0>
 ~~~
 
@@ -61,12 +58,9 @@ Notice that the address of the computer memory where your object is stored is al
 
 ## Object Methods 
 
-We have already discussed that classes/objects can have methods just like functions except that we have an extra `self` variable. We will now see an example.
+We have already discussed that classes/objects can have methods just like functions except that we have an extra `self` variable. We will now see an example (save as `method.py`).
 
 ~~~python
-#!/usr/bin/python
-# Filename: method.py
-
 class Person:
     def sayHi(self):
         print('Hello, how are you?')
@@ -80,7 +74,7 @@ p.sayHi()
 Output:
 
 ~~~
-$ python method.py
+$ python3 method.py
 Hello, how are you?
 ~~~
 
@@ -94,12 +88,9 @@ There are many method names which have special significance in Python classes. W
 
 The `__init__` method is run as soon as an object of a class is instantiated. The method is useful to do any *initialization* you want to do with your object. Notice the double underscores both at the beginning and at the end of the name.
 
-Example:
+Example (save as `class_init.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: class_init.py
-
 class Person:
     def __init__(self, name):
         self.name = name
@@ -115,7 +106,7 @@ p.sayHi()
 Output:
 
 ~~~
-$ python class_init.py
+$ python3 class_init.py
 Hello, my name is Swaroop
 ~~~
 
@@ -135,12 +126,9 @@ There are two types of *fields* - class variables and object variables which are
 
 *Class variables* are shared - they can be accessed by all instances of that class. There is only one copy of the class variable and when any one object makes a change to a class variable, that change will be seen by all the other instances.
 
-*Object variables* are owned by each individual object/instance of the class. In this case, each object has its own copy of the field i.e. they are not shared and are not related in any way to the field by the same name in a different instance. An example will make this easy to understand:
+*Object variables* are owned by each individual object/instance of the class. In this case, each object has its own copy of the field i.e. they are not shared and are not related in any way to the field by the same name in a different instance. An example will make this easy to understand (save as `objvar.py`):
 	
 ~~~python
-#!/usr/bin/python
-# Filename: objvar.py
- 
 class Robot:
     '''Represents a robot, with a name.'''
 
@@ -198,6 +186,7 @@ Robot.howMany()
 Output:
 
 ~~~
+$ python3 objvar.py
 (Initializing R2-D2)
 Greetings, my masters call me R2-D2.
 We have 1 robots.
@@ -268,12 +257,9 @@ Also observe that we *reuse* the code of the parent class and we do not need to
 
 The `SchoolMember` class in this situation is known as the *base class* or the *superclass*. The `Teacher` and `Student` classes are called the *derived classes* or *subclasses*.
 
-We will now see this example as a program.
+We will now see this example as a program (save as `inherit.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: inherit.py
-
 class SchoolMember:
     '''Represents any school member.'''
     def __init__(self, name, age):
@@ -320,7 +306,7 @@ for member in members:
 Output:
 
 ~~~
-$ python inherit.py
+$ python3 inherit.py
 (Initialized SchoolMember: Mrs. Shrividya)
 (Initialized Teacher: Mrs. Shrividya)
 (Initialized SchoolMember: Swaroop)

+ 9 - 16
14-io.pd

@@ -8,10 +8,9 @@ Another common type of input/output is dealing with files. The ability to create
 
 ## Input from user
 
-~~~python
-#!/usr/bin/python
-# user_input.py
+Save this program as `user_input.py`:
 
+~~~python
 def reverse(text):
     return text[::-1]
 
@@ -28,15 +27,15 @@ else:
 Output:
 
 ~~~
-$ python user_input.py
+$ python3 user_input.py
 Enter text: sir
 No, it is not a palindrome
 
-$ python user_input.py
+$ python3 user_input.py
 Enter text: madam
 Yes, it is a palindrome
 
-$ python user_input.py
+$ python3 user_input.py
 Enter text: racecar
 Yes, it is a palindrome
 ~~~
@@ -61,12 +60,9 @@ Homework exercise
 
 You can open and use files for reading or writing by creating an object of the `file` class and using its `read`, `readline` or `write` methods appropriately to read from or write to the file. The ability to read or write to the file depends on the mode you have specified for the file opening. Then finally, when you are finished with the file, you call the `close` method to tell Python that we are done using the file.
 
-Example:
+Example (save as `using_file.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: using_file.py
- 
 poem = '''\
 Programming is fun
 When the work is done
@@ -90,7 +86,7 @@ f.close() # close the file
 Output:
 
 ~~~
-$ python using_file.py
+$ python3 using_file.py
 Programming is fun
 When the work is done
 if you wanna make your work also fun:
@@ -113,12 +109,9 @@ Now, check the contents of the `poem.txt` file to confirm that the program has i
 
 Python provides a standard module called `pickle` using which you can store **any** Python object in a file and then get it back later. This is called storing the object *persistently*.
 
-Example:
+Example (save as `pickling.py`):
 
 ~~~python
-#!/usr/bin/python
-# Filename: pickling.py
- 
 import pickle
  
 # the name of the file where we will store the object
@@ -142,7 +135,7 @@ print(storedlist)
 Output:
 
 ~~~
-$ python pickling.py
+$ python3 pickling.py
 ['apple', 'mango', 'carrot']
 ~~~
 

+ 14 - 18
15-exceptions.pd

@@ -39,10 +39,9 @@ Python raises an error called `EOFError` which basically means it found an *end
 
 We can handle exceptions using the `try..except` statement.  We basically put our usual statements within the try-block and put all our error handlers in the except-block.
 
-~~~python
-#!/usr/bin/python
-# Filename: try_except.py
+Example (save as `try_except.py`):
 
+~~~python
 try:
     text = input('Enter something --> ')
 except EOFError:
@@ -56,15 +55,15 @@ else:
 Output:
 
 ~~~
-$ python try_except.py
+$ python3 try_except.py
 Enter something -->     # Press ctrl-d
 Why did you do an EOF on me?
 
-$ python try_except.py
+$ python3 try_except.py
 Enter something -->     # Press ctrl-c
 You cancelled the operation.
 
-$ python try_except.py
+$ python3 try_except.py
 Enter something --> no exceptions
 You entered no exceptions
 ~~~
@@ -87,10 +86,9 @@ You can *raise* exceptions using the `raise` statement by providing the name of
 
 The error or exception that you can raise should be a class which directly or indirectly must be a derived class of the `Exception` class.
 
-~~~python
-#!/usr/bin/python
-# Filename: raising.py
+Example (save as `raising.py`):
 
+~~~python
 class ShortInputException(Exception):
     '''A user-defined exception class.'''
     def __init__(self, length, atleast):
@@ -115,11 +113,11 @@ else:
 Output:
 
 ~~~
-$ python raising.py
+$ python3 raising.py
 Enter something --> a
 ShortInputException: The input was 1 long, expected at least 3
 
-$ python raising.py
+$ python3 raising.py
 Enter something --> abc
 No exception was raised.
 ~~~
@@ -134,10 +132,9 @@ In the `except` clause, we mention the class of error which will be stored `as`
 
 Suppose you are reading a file in your program. How do you ensure that the file object is closed properly whether or not an exception was raised? This can be done using the `finally` block. Note that you can use an `except` clause along with a `finally` block for the same corresponding `try` block. You will have to embed one within another if you want to use both.
 
-~~~python
-#!/usr/bin/python
-# Filename: finally.py
+Save as `finally.py`:
 
+~~~python
 import time
 
 try:
@@ -158,7 +155,7 @@ finally:
 Output:
 
 ~~~
-$ python finally.py
+$ python3 finally.py
 Programming is fun
 When the work is done
 if you wanna make your work also fun:
@@ -176,10 +173,9 @@ Observe that the `KeyboardInterrupt` exception is thrown and the program quits.
 
 Acquiring a resource in the `try` block and subsequently releasing the resource in the `finally` block is a common pattern. Hence, there is also a `with` statement that enables this to be done in a clean manner:
 
-~~~python
-#!/usr/bin/python
-# Filename: using_with.py
+Save as `using_with.py`:
 
+~~~python
 with open("poem.txt") as f:
     for line in f:
         print(line, end='')

+ 22 - 20
16-standard-library.pd

@@ -2,7 +2,7 @@
 
 The Python Standard Library contains a huge number of useful modules and is part of every standard Python installation. It is important to become familiar with the Python Standard Library since many problems can be solved quickly if you are familiar with the range of things that these libraries can do.
 
-We will explore some of the commonly used modules in this library. You can find complete details for all of the modules in the Python Standard Library in the ['Library Reference' section](http://docs.python.org/3.0/library/) of the documentation that comes with your Python installation.
+We will explore some of the commonly used modules in this library. You can find complete details for all of the modules in the Python Standard Library in the ['Library Reference' section](http://docs.python.org/py3k/library/index.html) of the documentation that comes with your Python installation.
 
 Let us explore a few useful modules.
 
@@ -17,10 +17,11 @@ The `sys` module contains system-specific functionality. We have already seen th
 Suppose we want to check the version of the Python command being used so that, say, we want to ensure that we are using at least version 3. The `sys` module gives us such functionality.
 
 ~~~
+$ python3
 >>> import sys
 >>> sys.version_info
-(3, 0, 0, 'beta', 2)
->>> sys.version_info[0] >= 3
+sys.version_info(major=3, minor=3, micro=0, releaselevel='final', serial=0)
+>>> sys.version_info.major >= 3
 True
 ~~~
 
@@ -28,11 +29,11 @@ How It Works:
 
 The `sys` module has a `version_info` tuple that gives us the version information. The first entry is the major version. We can check this to, for example, ensure the program runs only under Python 3.0:
 
+Save as `versioncheck.py`:
+
 ~~~python
-#!/usr/bin/python
-# Filename: versioncheck.py
 import sys, warnings
-if sys.version_info[0] < 3:
+if sys.version_info.major < 3:
     warnings.warn("Need Python 3.0 for this program to run",
         RuntimeWarning)
 else:
@@ -42,7 +43,7 @@ else:
 Output:
 
 ~~~
-$ python2.5 versioncheck.py
+$ python2.7 versioncheck.py
 versioncheck.py:6: RuntimeWarning: Need Python 3.0 for this program to run
   RuntimeWarning)
 
@@ -58,9 +59,9 @@ We use another module from the standard library called `warnings` that is used t
 
 What if you wanted to have some debugging messages or important messages to be stored somewhere so that you can check whether your program has been running as you would expect it? How do you "store somewhere" these messages? This can be achieved using the `logging` module.
 
+Save as `use_logging.py`:
+
 ~~~python
-#!/usr/bin/python
-# Filename: use_logging.py
 import os, platform, logging
 
 if platform.platform().startswith('Windows'):
@@ -85,16 +86,16 @@ logging.warning("Dying now")
 Output:
 
 ~~~
-$python use_logging.py
+$ python3 use_logging.py
 Logging to C:\Users\swaroop\test.log
 ~~~
 
 If we check the contents of `test.log`, it will look something like this:
 
 ~~~
-2008-09-03 13:18:16,233 : DEBUG : Start of the program
-2008-09-03 13:18:16,233 : INFO : Doing something
-2008-09-03 13:18:16,233 : WARNING : Dying now
+2012-10-26 16:52:41,339 : DEBUG : Start of the program
+2012-10-26 16:52:41,339 : INFO : Doing something
+2012-10-26 16:52:41,339 : WARNING : Dying now
 ~~~
 
 How It Works:
@@ -115,15 +116,16 @@ How much fun would it be if we could write our own program that will get search
 
 This can be achieved using a few modules. First is the `urllib` module that we can use to fetch any webpage from the internet. We will make use of Yahoo! Search to get the search results and luckily they can give us the results in a format called JSON which is easy for us to parse because of the built-in `json` module in the standard library.
 
-**TODO** Use some other example that doesn't use YUI API, maybe twitter firehose, etc.
+TODO
 
-~~~python
-#!/usr/bin/python
-# Filename: yahoo_search.py
+:   Does this yahoo search example work as expected?
 
+Save as `yahoo_search.py`:
+
+~~~python
 import sys
-if sys.version_info[0] != 3:
-    sys.exit('This program needs Python 3.0')
+if sys.version_info.major < 3:
+    sys.exit('This program needs Python 3')
 
 import json
 import urllib, urllib.parse, urllib.request, urllib.response
@@ -169,7 +171,7 @@ We make a connection to this URL using the `urllib.request.urlopen()` function a
 
 ## Module of the Week Series 
 
-There is much more to be explored in the standard library such as [debugging](http://docs.python.org/dev/library/pdb.html), [handling command line options](http://docs.python.org/3.0/library/getopt.html), [regular expressions](http://www.diveintopython.org/regular_expressions/index.html) and so on.
+There is much more to be explored in the standard library such as [debugging](http://docs.python.org/py3k/library/pdb.html), [handling command line options](http://docs.python.org/py3k/library/argparse.html), [regular expressions](http://docs.python.org/py3k/library/re.html) and so on.
 
 The best way to further explore the standard library is to read Doug Hellmann's excellent [Python Module of the Week](http://www.doughellmann.com/projects/PyMOTW/) series or reading the [Python documentation](http://docs.python.org/py3k/).
 

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 19 - 47
17-more.pd


+ 9 - 27
18-what-next.pd

@@ -8,11 +8,11 @@ I would suggest that you tackle this problem:
 
 This is fairly easy if you think about it in terms of all the various stuff that we have come across till now. If you still want directions on how to proceed, then here's a hint.
 
-Hint (Don't read)
+Hint (Don't read without trying first)
 
 :   Create a class to represent the person's information. Use a dictionary to store person objects with their name as the key. Use the pickle module to store the objects persistently on your hard disk. Use the dictionary built-in methods to add, delete and modify the persons.
 
-Once you are able to do this, you can claim to be a Python programmer. Now, immediately [send me a mail](http://www.swaroopch.com/contact/) thanking me for this great book ;-) . This step is optional but recommended. Also, please consider [buying a printed copy](http://www.swaroopch.com/buybook/) to support the continued development of this book.
+Once you are able to do this, you can claim to be a Python programmer. Now, immediately [send me an email](http://www.swaroopch.com/contact/) thanking me for this great book ;-). This step is optional but recommended. Also, please consider [buying a printed copy](http://www.swaroopch.com/buybook/) to support the continued development of this book.
 
 If you found that program easy, here's another one:
 
@@ -22,56 +22,38 @@ The replace command can be as simple or as sophisticated as you wish, from simpl
 
 After that, below are some ways to continue your journey with Python:
 
-## Exercises 
-
-There is a good discussion over at Stack Overflow on [regarding Python exercises to hone your skills](http://stackoverflow.com/questions/29578/python-exercises-to-hone-your-skills).
-
 ## Example Code 
 
 The best way to learn a programming language is to write a lot of code and read a lot of code:
 
-- [The PLEAC project](http://pleac.sourceforge.net/pleac_python/index.html)
-- [Rosetta code repository](http://www.rosettacode.org/wiki/Category:Python)
-- [Python examples at java2s](http://www.java2s.com/Code/Python/CatalogPython.htm)
 - [Python Cookbook](http://code.activestate.com/recipes/langs/python/) is an extremely valuable collection of recipes or tips on how to solve certain kinds of problems using Python. This is a must-read for every Python user.
+- [Python Module of the Week](http://www.doughellmann.com/PyMOTW/contents.html) is another excellent must-read guide to the [Python Standard Library](#standard-library).
 
 ## Questions and Answers
 
-- [Official Python Dos and Don'ts](http://docs.python.org/dev/howto/doanddont.html)
+- [Official Python Dos and Don'ts](http://docs.python.org/py3k/howto/doanddont.html)
 - [Official Python FAQ](http://www.python.org/doc/faq/general/)
 - [Norvig's list of Infrequently Asked Questions](http://norvig.com/python-iaq.html)
 - [Python Interview Q & A](http://dev.fyicenter.com/Interview-Questions/Python/index.html)
 - [StackOverflow questions tagged with python](http://beta.stackoverflow.com/questions/tagged/python)
 
-## Tips and Tricks 
-
-- [Python Tips & Tricks](http://www.siafoo.net/article/52)
-- [Advanced Software Carpentry using Python](http://ivory.idyll.org/articles/advanced-swc/)
-- [Charming Python](http://gnosis.cx/publish/tech_index_cp.html) is an excellent series of Python-related articles by David Mertz.
+## Tutorials
 
-## Books, Papers, Tutorials, Videos 
-
-The logical next step after this book is to read Mark Pilgrim's awesome [Dive Into Python](http://www.diveintopython.org) book which you can read fully online as well. The Dive Into Python book explores topics such as regular expressions, XML processing, web services, unit testing, etc. in detail.
+- [Awaretek's comprehensive list of Python tutorials](http://www.awaretek.com/tutorials.html)
 
-Other useful resources are:
+## Videos 
 
 - [PyVideo](http://www.pyvideo.org/category)
-- [ShowMeDo videos for Python](http://showmedo.com/videos/python)
-- [GoogleTechTalks videos on Python](http://youtube.com/results?search_query=googletechtalks+python)
-- [Awaretek's comprehensive list of Python tutorials](http://www.awaretek.com/tutorials.html)
-- [The Effbot's Python Zone](http://effbot.org/zone/ )
-- [Links at the end of every Python-URL! email](http://groups.google.com/group/comp.lang.python.announce/t/37de95ef0326293d)
-- [Python Papers](http://pythonpapers.org)
 
 ## Discussion 
 
-If you are stuck with a Python problem, and don't know whom to ask, then the [comp.lang.python discussion group](http://groups.google.com/group/comp.lang.python/topics) is the best place to ask your question.
+If you are stuck with a Python problem, and don't know whom to ask, then the [python-tutor list](http://mail.python.org/mailman/listinfo/tutor) is the best place to ask your question.
 
 Make sure you do your homework and have tried solving the problem yourself first.
 
 ## News 
 
-If you want to learn what is the latest in the world of Python, then follow the [Official Python Planet](http://planet.python.org) and/or the [Unofficial Python Planet](http://www.planetpython.org).
+If you want to learn what is the latest in the world of Python, then follow the [Official Python Planet](http://planet.python.org).
 
 ## Installing libraries 
 

+ 1 - 1
20-appendix-about.pd

@@ -22,7 +22,7 @@ I used Vim for editing thanks to the [ViewSourceWith extension for Firefox](http
 
 ## Now
 
-Using Vim, Pandoc, and Mac OS X.
+Using [Vim](http://www.swaroopch.com/notes/vim), [Pandoc](http://johnmacfarlane.net/pandoc/README.html), and Mac OS X.
 
 ## About The Author 
 

+ 1 - 1
21-revision-history.pd

@@ -2,7 +2,7 @@
 
 - 2.0
     - 20 Oct 2012
-    - Rewriting using [Pandoc](http://johnmacfarlane.net/pandoc/README.html), thanks to my wife!
+    - Rewritten in [Pandoc format](http://johnmacfarlane.net/pandoc/README.html), thanks to my wife who did most of the conversion from the Mediawiki format
     - Simplifying text, removing non-essential sections such as `nonlocal` and metaclasses
 - 1.90 
     - 04 Sep 2008 and still in progress