## 2011年12月30日 星期五

### [ The python tutorial ] 3. An Informal Introduction to Python

3.1. Using Python as a Calculator
Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>>. (It shouldn’t take long.

- Numbers

>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2 # and a comment on the same line as code
4
>>> (50-5*6)/4
5.0
>>> 8/5 # Fractions aren't lost when dividing integers
1.6

>>> # Integer division returns the floor:
... 7//3
2
>>> 7//-3
-3

>>> x = y = z = 0 # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0

>>> # try to access an undefined variable
... n
Traceback (most recent call last):
File "", line 1, in
NameError: name 'n' is not defined

>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0, 1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)

>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5

>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
File "", line 1, in ?
TypeError: can't convert complex to float; use abs(z)
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a) # sqrt(a.real**2 + a.imag**2)
5.0

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

- Strings

>>> 'spam eggs'
'spam eggs'
>>> 'doesn\'t'
"doesn't"
>>> "doesn't"
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'

hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant."

print(hello)

>>> word
'HelpA'
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'

>>> word[:2] # The first two characters
'He'
>>> word[2:] # Everything except the first two characters
'lpA'

Python 的字串是 immutable 的, 也就是你不能使用 [] 改變它的值 :
>>> word[0] = 'x'
Traceback (most recent call last):
File "", line 1, in ?
TypeError: 'str' object does not support item assignment
>>> word[:1] = 'Splat'
Traceback (most recent call last):
File "", line 1, in ?
TypeError: 'str' object does not support slice assignment

>>> word[:2] + word[2:] # s[:i] + s[i:] equals s.
'HelpA'
>>> word[:3] + word[3:]
'HelpA'

>>> word[1:100] # 範圍超過, 頂多印到字串尾
'elpA'
>>> word[10:]
''
>>> word[2:1]
''

>>> word[-1] # The last character
'A'
>>> word[-2] # The last-but-one character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # Everything except the last two characters
'Hel'

>>> word[-100:]
'HelpA'
>>> word[-10] # error
Traceback (most recent call last):
File "", line 1, in ?
IndexError: string index out of range

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

Sequence Types — str, bytes, bytearray, list, tuple, range
Strings are examples of sequence types, and support the common operations supported by such types.

String Methods
Strings support a large number of methods for basic transformations and searching.

String Formatting
Information about string formatting with str.format() is described here.

Old String Formatting Operations
The old formatting operations invoked when strings and Unicode strings are the left operand of the % operator are described in more detail here.

Unicode 從 Python 3.0 以後開始支援. 在某些時候你需要 Unicode 內的字符時, 可以使用 Unicode-Escape encoding :
>>> 'Hello\u0020World !' # \u0020=0x0020 是空白
'Hello World !'

>>> "李".encode('utf-8')
b'\xe6\x9d\x8e'

- Lists

>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]

>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> # Insert (a copy of) itself at the beginning
>>> a[:0] = a
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>> # Clear the list: replace all items with an empty list
>>> a[:] = []
>>> a
[]

>>> a = ['a', 'b', 'c', 'd']
>>> len(a)
4

>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2

>>> p[1].append('xtra')
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q # 因為是 shallow copy, 所以原有串列的值也會改變
[2, 3, 'xtra']

3.2 First Steps Towards Programming

1. a, b = 01

1. int t = b
2. b = a + b
3. a = t

### [Quick Python] 3. The Quick Python overview

以下內容來自 "The Quick Python Book" :

Preface :
The purpose of this chapter is to give you a basic feeling for the syntax, semantics, capabilities, and philosophy of the Python language. It has been designed to provide you with an initial perspective or conceptual framework on which you'll be able to add details as you encounter them in the rest of the book.

On an initial read read, you needn't be concerned about working through and understanding the details of the code segments. You'll be doing fine if you pick up a bit of an idea about what is being done. The subsequent chapters of this book will walk you through the specifics of these features and won't assume prior knowledge. You can always return to this chapter and work though the examples in the appropriate sections as review after you've red the later chapters.

Python synopsis :
Python has a number of built-in data types such as integers, floats, complex numbers, strings, lists, tuples, dictionaries and file objects. These can be manipulated using language operators, built-in functions, library functions, or a data type' sown methods.

Programmers can also define their own classes and instantiate their own class instances. These can be manipulated by programmer-defined methods as well as the language operators and built-in functions for which the programmer has defined the appropriate special method attributes. Python provides conditional and iterative control flow through an if-elif-else construct along with while and for loops. It allows function definition with flexible argument-passing options. Exceptions (error) can be raised using the raise statement and caught and handled using the try-except-else construct.

Variables don't have to be declared and can have any built-in data type, user-defined object, function, or module assigned to them.

Built-in data types
Python has several built-in data types, from scalars like numbers and Booleans, to more complex structures like lists, dictionaries and files.
- Numbers
Python's four number types are integers, floats, complex numbers and Booleans :
* Integer - 1, -3, 42, 355, 88888888, -7777
* Floats - 3.0, 31e12, -6e-4
* Complex numbers - 3+2j, -4-2j, 4.2+6.3j
* Booleans - True, False

You can manipulate them using the arithmetic operators : +(addition), -(subtraction), *(multiplication), /(division), **(exponentiation), and %(modulus). The following examples use integers :

Division of integers with / (1) results in a float (new in Python 3.x), and division of integers with // (2) results in truncation. Note that integers are of unlimited size(3), they will grow as large as you need them to. These examples work with floats, which are based on the doubles in C. Next, the following examples use complex numbers :

Complex numbers consists of both a real element and an imaginary element, suffixed with a j. In the preceding code, variable x is assigned to a complex number. You can obtain its "real" part using the attribute notation x.real
Several built-in functions can operate on numbers. There are also the library module cmath (which contains functions for complex numbers) and the library module math(which contains functions for the other three types) :

Built-in functions are always available and are called using a standard function calling syntax. In the preceding code, round() is called with a float as its input argument. The functions in library modules are made available using the import statement. At (2), the math library module is imported, and its cell() function is called using attribute notation : module.function(arguments)

The following examples use Booleans :

Other than their representation as True and False, Booleans behave like the number 1 (True) and 0 (False).

- Lists
Python has a powerful built-in list type :
[]
[1]
[1, 2, 3, 4, 5]
[1, "two", 3L, 4.0, ["a", "b"], (5,6)] <---(1)

A list can contain a mixture of other types as its elements, including strings, tuples, lists, dictionaries, functions, file objects and any type of number (1). A list can be indexed from its front or back. You can also refer to a subsegment, or slice, of a list using slice notation :

Obtain a slice using [m:n] (3), where m is the inclusive starting point and n is the exclusive ending point. An [:n] slice (4) starts at its beginning, and an [m:] slice goes to a list's end. You can use this notation to add, remove, and replace elements in a list or to obtain an element or a new list that is a slice from it :

Some built-in functions (lenmax and min), some operators (in+, and *), the del statement, and the list methods (appendcountextendindexinsertpopremove,reverse, and sort) will operate on lists :

The operators + and * each create a new list, leaving the original unchanged (1). A list's methods are called using attribute notation on the list itself :x.method(arguments)

- Tuples
Tuples are similar to lists but are immutable - that is, they can't be modified after they have been created. The operators (in+ and *) and built-in functions (lenmax, andmin), operate on them the same way as they do on lists, because none of them modify the original. Index and slice notation work the same way for obtaining elements or slices but can't be used to add, remove or replace elements. There are also only two tuple methods : count() and index()A major purpose of tuples is for use as keys for dictionaries. They're also more efficient to use when you don't need modification.
()
(1,) <--- (1)
(1, 2, 3, 4, 5)
(1, "two", 3L, 4.0, ["a","b"], (5, 6)) <--- (2)

A one-element tuple (1) needs a comma. A tuple, like a list, can contain a mixture of other types as its elements (2). A list can be converted to a tuple using the bulit-in function tuple() :
>>> x = [1, 2, 3, 4]
>>> tuple(x)
(1, 2, 3, 4)

Conversely, a tuple can be converted to a list using the built0in function list() :
>>> x = (1, 2, 3, 4)
>>> list(x)
[1, 2, 3, 4]

- Strings
String processing is one of Python's strengths. There are many options for delimiting strings :
"A string in double quotes can obtain 'single quote' characters."
'A string in single quotes can obtain "double quote" characters.'
'''\This string starts with a tab and ends with a newline character.\n'''
"""This is a triple double quoted string, the only kind that can contain real newlines."""

String can be delimited by singe (' '), double (" "), triple single (''' '''), or triple double (""" """) quotations and can contain tab(\t) and newline (\n) characters. Strings are also immutable. The operators and functions that work with them return new strings derived from the original. The operators (in+, and *) and built-in functions (lenmaxand min) operate on strings as they do on lists and tuples. Index and slice notation works the same for obtaining elements or slices but can't be used to add, remove, or replace elements. Strings have several methods to work with their contents, and the re library module also contains functions for working with strings :

The print() function output strings. Other python data types can be easily converted to strings and formatted :

- Dictionaries
Python's built-in dictionary data type provides associate array functionality implemented using hash tables. The built-in len() function returns the number of key-value pairs in a dictionary. The del statement can be used to delete a key-value pair. As is the case for lists, a number of dictionary methods (clearcopygethas_keyitemskeys,update and values) are available :

Keys must be of an immutable type (1). This includes numbers, strings and tuple. Values can be any kind of object. The dictionary method get() optionally returns a user-definable value when a key isn't in the dictionary.

- Set
A set in Python is an unordered collection of objects, used in situations where membership and uniqueness in the set are the main things you need to know about that object. You can think of sets as a collection of dictionary keys without any associated values :

You can create a set by using set() on a sequence, like a list (1). When a sequence is made into a set, duplicates are removed (2). The in keyword (3) is used to check for membership of an object in a set.

- File objects
A file is accessed through a Python file object :

The open statement (1) creates a file object. Here the file myfile in the current working directory is being opened in write ("w") mode. After writing two lines to it and closing it (2), we open the same file again, this time in the read ("r") mode. The os module provides a number of functions for moving around the file system and working with the pathnames of files and directories. Here, we move to another directory (4). But by referring to the file by an absolute path name, we are still able to access it.
A number of other input/output capabilities are available. You can use the built-in input function to prompt and obtain a string from the user. The sys library module allows access to stdin, stdout, and stderr. The struct library module provides support for reading and writing files that were generated by or are to be used by C programs. ThePickle library module delivers data persistence through the ability to easily read and write the Python data types to and from files.

Control flow structures :
Python has a full range of structures to control code execution and program flow, including common branching and looping structures.

- Boolean values and expressions
Python has several ways of expressing Boolean values; the Boolean constant False, 0, the Python nil value None, and empty values (for example, the empty list [ ] or empty string ""are all taken as False. The Boolean constant True and everything else are considered True. You can create comparison expressions using the comparison operators (<, <=, ==, >, >=, !=, is, is not, in, not in) and the logical operators (and, not, or), which all return True or False.

- The if-elif-else statement
The block of code after the first true condition (of an if or an elif) is executed. If none of the conditions is true, the block of code after the else is executed :

The elif and else clauses are optional, and there can be any number of elif clauses. Python uses indentation to delimit blocks. No explicit delimiters such as brackets or braces are necessary. Each block consists of one or more statements separated by newlines. These statements must all be at the same level of indentation.

- The while loop
The while loop is executed as long as the condition (which here is x > y) is true :

First line is a shorthand notation. Here, u and v are assigned a value of 0, x is set to 100, and y obtains a value of 30. After while statement is the loop block. It’s possible for it to contain break (which ends the loop) and continue statements (which abort the current iteration of the loop).

- The for loop
The for loop is simple but powerful because it’s possible to iterate over any iterable type, such as a list or tuple. Unlike in many languages, Python’s for loop iterates over each of the items in a sequence, making it more of a foreach loop. The following loop finds the first occurrence of an integer that is divisible by 7:

x is sequentially assigned each value in the list (1). If x isn’t an integer, then the rest of this iteration is aborted by the continue statement (2). Flow control continues with x set to the next item from the list. After the first appropriate integer is found, the loop is ended by the break statement (3).

- Function definition
Python provides flexible mechanisms for passing arguments to functions :

Functions are defined using the def statement (1). The return statement (2) is what a function uses to return a value. This value can be of any type. If no return statement is encountered, Python’s None value is returned. Function arguments can be entered either by position or by name (keyword). Here z and y are entered by name (3). Function parameters can be defined with defaults that are used if a function call leaves them out (4). A special parameter can be defined that will collect all extra positional arguments in a function call into a tuple (5). Likewise, a special parameter can be defined that will collect all extra keyword arguments in a function call into a dictionary (6).

- Exceptions
Exceptions (errors) can be caught and handled using the try-except-finally-else compound statement. This statement can also catch and handle exceptions you define and raise yourself. Any exception that isn’t caught will cause the program to exit. Below shows basic exception handling :

Here we define our own exception type inheriting from the base Exception type (1). If an IOError or EmptyFileError occurs during the execution of the statements in thetry block, the associated except block is executed (2). This is where an IOError might be raised (3). Here we raise the EmptyFileError (4). The else clause is optional (5). It’s executed if no exception occurs in the try block (note that in this example, continue statements in the except blocks could have been used instead). The finally clause is optional (6). It’s executed at the end of the block whether an exception was raised or not.

Module creation :
It’s easy to create your own modules, which can be imported and used in the same way as Python’s built-in library modules. The example below is a simple module with one function that prompts the user to enter a filename and determines the number of times words occur in this file :
- wo.py :
1. """wo module. Contains function: words_occur()"""
2. interface functions
3. def words_occur():
4.     """words_occur() - count the occurences of words in a file."""
5.     # Prompt user for the name of the file to use. (1)
6.     file_name = input("Enter the name of the file: ")
7.     # Open the file, read it and store its words in a list.
8.     f = open(file_name, 'r')
9.     word_list = f.read().split() # (2)
10.     f.close()
11.     # Count the number of occurences of each word in the file.
12.     occurs_dict = {}
13.     for word in word_list:
14.         # increment the occurences count for this word
15.         occurs_dict[word] = occurs_dict.get(word, 0) + 1
16.     # Print out the results. (3)
17.     print("File %s has %d words (%d are unique)" \
18.           % (file_name, len(word_list), len(occurs_dict)))
19.     print(occurs_dict)
20.
21. #(4)
22. if __name__ == '__main__':
23.     words_occur()

Comments are anything beginning with a # character (1). read() returns a string containing all the characters in a file (2), and split() returns a list of the words of a string "split out" based on whitespace. You can use a \ to break a long statement across multiple lines (3). This allows the program to also be run as a script by typing python wo.py at a command line (4).
If you place a file in one of the directories on the module search path, which can be found in sys.path, then it can be imported like any of the built-in library modules using the import statement :
>>> import wo
>>> wo.words_occur()
Enter the name of the file:

If you change the file wo.py on disk, import won’t bring changes in to the same interactive session. You use the reload() function from the imp library in this situation :
>>> import imp
wo' from 'wo.py'>

For larger projects, there is a generalization of the module concept called packages. This allows you to easily group a number of modules together in a directory or directory subtree and import and hierarchically refer to them using a package.subpackage. module syntax. This entails little more than the creation of a possibly empty initialization file for each package or subpackage.

Object-oriented programming :
Python provides full support for OOP. Below is an simple example that might be the start of a simple shapes module for a drawing program :
- sh.py :
1. """sh module. Contains classes Shape, Square and Circle"""
2. class Shape: # (1)
3.     """Shape class: Has method move"""
4.     def __init__(self, x, y):  # (2)
5.         self.x = x  # (3)
6.         self.y = y
7.     def move(self, deltaX, deltaY):   # (4)
8.         self.x = self.x + deltaX
9.         self.y = self.y + deltaY
10.
11. class Square(Shape):
12.     """Square class: Inherits from Shape"""
13.     def __init__(self, side=1, x=0, y=0):
14.         Shape.__init__(self, x, y)
15.         self.side = side
16.
17. class Circle(Shape): # (5)
18.     """Circle class: Inherits from Shape and has method area"""
19.     pi = 3.14159  # (6)
20.     def __init__(self, r=1, x=0, y=0):
21.         Shape.__init__(self, x, y)  # (7)
23.     def area(self):
24.         """Circle area method: Returns the area of the circle."""
26.     def __str__(self):  # (8)
27.         return "Circle of radius %s at coordinates (%d, %d)" \