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

更多有關於浮點數可以參考 Floating Point Arithmetic: Issues and Limitations, 要注意的是整數相除在 Python 會產生浮點數! 

如果在整數相除想得到捨棄小數點的整數結果, 可以考慮運算子 // : 
>>> # Integer division returns the floor:
... 7//3
2
>>> 7//-3
-3

符號 '=' 在 Python 用來賦值, 你可以在一行對多個變數賦值 : 
>>> x = y = z = 0 # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0

在 Python 的變數在 access 前必須要先賦值 ("defined" - assigned a value), 否則會有例外發生 : 
>>> # try to access an undefined variable
... n
Traceback (most recent call last):
File "", line 1, in
NameError: name 'n' is not defined

另外 Python 也支援 複數 型態. 你可以使用語法 real+imagj 賦值, 或是透過函示 complex(real, imag) 也可以 : 
>>> 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)

如果你要從一個複數 z 取出實數與虛數, 可以使用該複數的 attribute real/imag, 如 z.real and z.imag : 
>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5

底下為一些對複數操作的範例, 你可以使用函數 abs(z) 取得複數的 "magnitude", 但是不能使用函數 float() 或 int() 對複數做轉換 : 
>>> 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

在 Interactive mode, 上一次操作的結果會被存放在變數 _ : 
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

對於上面介紹的特數變數 "_" 最好不要取跟它同名的變數或是對它進行賦值, 否則你便無法使用該變數的特殊功能 : 

- Strings 
在 Python 中的字串可以用 single/double quote 來包住, 底下為簡單範例 : 
>>> '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.'

如果字串有跨行, 你可以使用 backslash "\", 這樣下一行跟上一行便會自動串接, 在很長的字串或多行字串很有用 : 
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)

上面範例的換行需要用 '\n' 來表示, 如果你想要讓代碼中字串的換行就直接代表換行, 可以考慮 triple quote """ 或 ''' : 
 

如果你想要讓 '\n' 就是字面上的字元而不是換行時, 可以在前面加 "r" : 
 

字串可以透過符號 + 進行串接, 或是透過符號 * 進行重複 : 
 

兩個相臨的字串會被自動串接 : 
 

在 Python 沒有所謂 Char 型態, char 就是長度為一的字串, 你可以使用 index 的方式取的字串中的某個 char, 第一個字元的 index=0, 或是透過 slice [m:n] 操作多個字元 : 
>>> word
'HelpA'
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'

事實上 slice 也可以這樣用 : 
>>> 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'

如果再使用 slice 時, 範圍超過或不在原有字串中, 則空字串會被返回 : 
>>> word[1:100] # 範圍超過, 頂多印到字串尾
'elpA'
>>> word[10:]
''
>>> word[2:1]
''

你也可以使用負值來告訴 slice 從右邊數過來 : 
>>> 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'

如果在 slice 使用負數但又超過範圍 : 
>>> word[-100:]
'HelpA'
>>> word[-10] # error
Traceback (most recent call last):
File "", line 1, in ?
IndexError: string index out of range

如果你要知道字串的長度可以使用函數 len() : 
>>> 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.

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

如果你想轉變字串編碼到特定編碼, 可以使用字串自帶方法 encode(), 並將你想轉換成的編碼名稱用小寫當作參數傳入 : 
>>> "李".encode('utf-8')
b'\xe6\x9d\x8e'

- Lists 
串列為使用 [ ] 將元素包括, 並以 ',' 區隔. 跟字串一樣, 你也可以使用 index 或是 slice 來取得串列中的元素 : 
 

使用 slice 返回的串列是新的串列, 但是串列中的元素還是舊的串列中的元素. (shallow copy), 另外串列中的元素你是可以改變的 : 
>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]

使用 slice 來對串列賦值很方便, 但是也有可能改變原有串列的大小喔 : 
>>> # 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
[]

使用函數 len() 可以知道串列元素個數 : 
>>> 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

如果要加元素到串列, 可以使用函數 append() : 
>>> p[1].append('xtra')
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q # 因為是 shallow copy, 所以原有串列的值也會改變
[2, 3, 'xtra']

3.2 First Steps Towards Programming 
底下我們透過前面介紹的內容, 簡單寫一個 費比係數 的產生函數 : 
 

天啊. 程式碼怎麼這麼短! 這是因為 Python 的某些特性讓我們少寫很多代碼, 首先是你可以使用所謂的 "multiple assignment" : 
如果是其他語言的話, 可能就需要兩行 "a=0" 與 "b=1". 另外便是 while loop 的程式碼區塊並不需要 "{}", 原因是 Python 使用縮排來區分程式碼區塊. 最後是在處理 費比數列 中當前數為前兩數相加, 其他語言可能會是如下撰寫 : 
  1. int t = b  
  2. b = a + b  
  3. a = t  
但這邊卻只需要 "a, b = b, a+b" ! 那也是 "multiple assignment" 好用的地方.

[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
>>> imp.reload(wo)
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)  
  22.         self.radius = r  
  23.     def area(self):  
  24.         """Circle area method: Returns the area of the circle."""  
  25.         return self.radius * self.radius * self.pi  
  26.     def __str__(self):  # (8)  
  27.         return "Circle of radius %s at coordinates (%d, %d)" \  
  28.                % (self.radius, self.x, self.y)  

Classes are defined using the class keyword (1). The instance initializer method (constructor) for a class is always called __init__ (2). Instance variables x and y are created and initialized here (3). Methods, like functions, are defined using the def keyword (4). The first argument of any method is by convention called self. When the method is invoked, self is set to the instance that invoked the method. Class Circle inherits from class Shape (5). This is similar to but not exactly like a standard class variable (6). A class must, in its initializer, explicitly call the initializer of its base class (7). The __str__ method is used by the print function (8). Other special attribute methods permit operator overloading or are employed by built-in methods such as the length (len) function. 

Importing this file makes these classes available : 
 

The initializer is implicitly called, and a circle instance is created (1). The print function implicitly uses the special __str__ method (2). Here we see that the move method of Circle’s parent class Shape is available (3). A method is called using attribute syntax on the object instance: object.method(). The first (self) parameter is set implicitly.

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...