免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2301 | 回复: 0
打印 上一主题 下一主题

一篇台湾人写的Python入门文章(本人归纳)(1) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-10-27 16:22 |只看该作者 |倒序浏览
一:简单介绍
1.1任何語言的第一個範例
$ python
Python 2.2 (#3, Sep 1 2002, 20:55:03)
[GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-99)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print 'Hello, world!'
Hello, world!
>>> ^D
$
• 解譯式語言 (interpretive)
• 互動式 (interactive)
• 用 End-of-file (Linux: control-D, Windows: control-Z) 結束 python 解譯器

1.2許多語言的第二個範例: 當簡易計算機用
>>> 3+5
8
>>> x = 3**2.5 # 3**2.5 的計算結果用x 來記住
>>> y = 0
>>> x, y
(15.588457268119896, 0)
>>> x/y
Traceback (most recent call last):
File "", line 1, in ?
ZeroDivisionError: float division
• 加(+)、減(-)、乘(*)、除(/)、次方(**)、餘(%)
• 變數的指定和使用
• 準確位數 => 單精度還是雙精度?
• 錯誤(error)的顯示
• 註解

1.3第三個範例
• 工程計算機
>>> from math import *
>>> sqrt(3.0)
1.7320508075688772
>>> log10(2)
0.3010299956639812
>>> sin(pi/3)
0.8660254037844386
• math 模組的載入

1.4. 第四個範例
費伯納西數列 (Fibonacci series): A(i+1) = A(i) + A(i-1), A(1) = A(2) = 1
>>> a, b = 0, 1
>>> while b

                                二:Python 的特色 (Features)
• 解譯式 (interpretive)、互動式 (interactive)
• 模組化 (modular)
• 跨平台 (cross-platform): Linux、Windows、MacIntosh���許多 UN*Xes...
• 自由 (free software): 自由使用、自由研究、自由修改、自由散佈
• 動態定型 (dynamic typing): 不需要宣告變數型態
• 用內縮表示迴圈和其他的階層
• 內建物件型態 (built-in object types): list、dictionary、string、tuple
• 內建工具 (built-in tools): 切片 (slicing)、連接 (concatenating)、排序 (sorting)、映射
(mapping)、... 等等
• 函式庫: HTML、http、socket、正規表示式(regular expression)、圖形介面(GUI)... 等等
• 第三人工具 (third-party utilities): COM, XML, imaging, ... (自由真好!)
• 非強迫性的物件導向 (object-oriented): 想寫物件就寫物件, 不想寫物件也不會被強迫寫物件。
• 可與其他語言結合:
• 擴充 (extending): 讓 python 執行你的 C++ code
• 內嵌 (embedding): 讓 python 成為你的 C/C++/... 應用軟體的一部分
• 易學、易用


       三: 內建資料型態
1. 內建物件型態:數字 (Numbers)
• 浮點數: 3.1415, 6.02E23
• 整數: 100 (32 位元), 0324 , 0xA140
• 長整數: 5000000000  : 可用來精確表示政府預算
• 複數: 1-5j
z = 1-5j, w = 3j+2, z*w = ? w.real, w.imag, w.conjugate(), abs(w)
• 運算符: a = 5.1; b = 3; c = int(a)
• 加減乘除次方餘 + - * / ** %: 用 a 和 b 全部試一遍, a%b = ?
• 左括右括 ( ): a / (b-1) = ?
• 負號 -: -a = ?
• 整數的位元運算: 補數 ~ 左右移 > 和 & 或 | 互斥或 ^
~c = ?, c>b = ?, c&b = ?, c|b = ?, c^b = ?
• 優先順序 (precedence): 括弧 > 負號、補數 > 乘、除、餘 > 加、減 > 左移、右移 >
位元和 & > 位元互斥或 ^ > 位元或 |
同等優先的算符, 順序是由左而右


2. 內建物件型態:文字 (Text)
以字串(strings)為資料型態, 字串 = 一串字
• 單引號: 'this is a "single-quoted" string,\n don\'t you like it?'
• 雙引號: "this is a 'double-quoted' string"
• 三引號:
'''this is a triply-quoted string
字串中可以換行, 也可以用單引號和雙引號'''
字串的處理: s1 = 'Hello', s2 = 'World'
• 連接 (concatenate): s1+', '+s2 -> ?
• 重複 (repeat): '='*40 -> ?
• 索引 (index): s1[3] -> ?
• 循序取出單字 (iteration): for c in s1: print c,
• 單字搜尋 (membership): print 'ell' in s1
• 切片 (slice): s2[1:3] -> ?, s23 -> ?, s2[2:] -> ?, s2[:] -> ?, s2[-3:-1] -> ?, s2[-2:] -> ?
• 長度 (length): len(s1)
• 格式字串: str_student = '班上有 %d 個學生' % n
其他的格式: %f, %g, %e, %E, %x, %X, %s, ...


3. 內建容器型態:清單 (List)
>>> m = [1, 5, 7, -3, -1, 0]
>>> m.append(3)
>>> m
[1, 5, 7, -3, -1, 0, 3]
>>> del m[1:3]
>>> m
[1, -3, -1, 0, 3]
>>> m[-1]
3
• 中括號加逗號
• 索引和切片: 和字串類似
• 可變 (mutable)
>>> m[1] = -1; m # 換掉一個項目
[1, -1, -1, 0, 3]
>>> m[2:4] = ['Taipei', 'Tainan', 'Hsin-Chu', 'Taichung']; print m # 換掉一
些項目
[1, -1, 'Taipei', 'Tainan', 'Hsin-Chu', 'Taichung', 3]

4. 清單的操作 (List Operations)
m = [1, 3]
• m 是個物件 (object), 其型態 (type) 是清單
• m 有一些方法 (method) 可以用, 如下
• 添加: m.append('hi') -> [1, 3, 'hi']
• 擴充: m.extend([1,0,-1,-2]) -> [1, 3, 'hi', 1, 0, -1, -2]
• 移除: m.remove('hi') -> [1, 3, 1, 0, -1, -2]
• 插入: m.insert(-1, 3.5) -> [1, 3, 1, 0, -1, 3.5, -2]
• 彈出: m.pop() = -2 -> [1, 3, 1, 0, -1, 3.5]
m.pop(1) = 3 -> [1, 1, 0, -1, 3.5]
• 計數: m.count(1) -> 2
• 尋找位置: m.index(-1) -> 5, m.index(7) -> ValueError!
• 現場排序: m.sort() -> [-2, -1, 0, 1, 1, 3, 3.5 ]
• 逆轉: m.reverse() -> [3.5, 3, 1, 1, 0, -1, -2]
• 加、乘、len()?

5. 清單中有清單 (Lists in a List)
>>> a = 7
>>> m = [1, 5, a]
>>> a = -1
>>> m
[1, 5, 7]
>>> k = [3, m, 'hello']
>>> k
[3, [1, 5, 7], 'hello']
>>> k[1][2]
7
>>> m[1] = 0
>>> k
[3, [1, 0, 7], 'hello']
• 清單中的一般項目: 是複本 (copy)
• 清單中的清單: 是個參考 (reference), 不是複本 (為什麼?)

6. 清單的應用 (Using Lists)
• 當作堆疊 (stack):  用哪兩個操作進出?
• 當作列隊 (queue):  用哪兩個操作進出?

7. Tuple
• {Webster's dictionary} Tuple: [語源學] set of (so many) elements -- usually used of sets with
ordered elements . quintuple, sextuple
• 和清單相似, 是一些量的有序集合。
• 和清單最大的不同: 不能變
• 可以作為 dictionary 的鍵、函式回傳、多變數給值 ... 等等
• 小括號加逗號表示法, 小括弧視情況可省略
t = (-1, 3.5, 'hello')
x, y, z = 1, 2, 3

8. 序列 (Sequence)
• 有三種: 清單、tuple、字串
• 都有類似的運算: 索引、切片

9. 字典 (Dictionary)
• 鍵 (key) 和值 (value) 的對照表 --> 「關連式記憶」
>>> prices = { 'apple': 7.5, 'orange': 4.5, 'banana': 2}
>>> prices['orange'] # 用鍵當索引
4.5
>>> prices.has_key('tomato')
0
>>> prices.keys() # note (lack of) order
['orange', 'apple', 'banana']
>>> prices['guava'] = 6.7
>>> print prices['tomato']
Traceback (most recent call last):
File "", line 1, in ?
KeyError: 'tomato'
• 鍵必需是不可變的型態 (如: 常數、常字串、Tuple)
• 由 Tuple 建構字典:
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}


四: 流程控制
1. 流程控制 (Flow Control)
>>> a = '小華'
>>> if a == '小明':
... print '[%s]' % a
... elif not a == '小華':
... print '' % a
... else:
... print '(%s)' % a
...
(小華)
• if/elif 後的是邏輯表示式 (logic expression)
• 不用把 expression 括起來
• 內縮
• 在同一組邏輯分支中:
• if 只有一個
• elif 可以沒有或有多個
• else 可以沒有或有一個

2. 邏輯表示式 (Logic Expression)
• 表示式的值是偽(False、0、None、空序列即[]、()、) 或真 (True,非0的數,非空序列)
• 邏輯非 not、和 and 、或 or
• 在 in 、 不在 not in
• 比較算符: 相等 == 不相等 != 大於 > 小於 = 不大於  g 即等同於 a  g
• 優先順序: 在、不在 > 比較 > 非 > 和 > 或
• 用括弧括住要先算的部分
• 習題: 以下程式會印出什麼?
暗示: 檢查部分表示式是否足夠決定整個表示式的真偽 (「短路算符」)
>>> a, b = 5, 1
>>> def func(x):
... print 'x = %s in func' % s
... return 1
>>> a == 5 or func(a)
>>> a > b and func(b)

3. 迴圈 (Loops)
>>> m = ['apple', 'tangerine', 'banana']
>>> for fruit in m:
... print fruit, len(fruit)
... if fruit[0] > 'p':
... break
...
apple 5
tangerine 9
>>> i = 7
>>> while i > 0:
... print i**3,
... i -= 1
...
343 216 125 64 27 8 1
• 用不同的變數值反覆執行相同的程式區塊
• for loop 語法: for var in object: loopbody
• while loop 語法: while expression: loopbody
• 迴圈內容要內縮 (indent), 用一個跳格或一些空白, 同一階層的要用等量的空白, 空白行結束
一階層

4. 範圍函式 (The range() Function)
>>> range(10) # 包括0, 不包括10
[0, 1, 2, ... 9]
>>> range(3,6) # 包括3, 不包括6
[3, 4, 5]
>>> range(2,8,2) # 每步加2
[2, 4, 6]
>>> m = [x*x for x in range(4)] # 清單的內涵建構法(list comprehension)
>>> for i in range(len(m)): # 需要索引時
... print i, m
0 0
1 1
2 4
3 9
• 習題: 建構 [-30, -50, -70, -90] 的 range() 呼叫。 ## >>> range(-30,-100,-20) # 每步加 -20,
到大於或等於 -100 為止

5. 迴圈的分叉
• break: 跳出迴圈
• continue: 略過區塊的以下部分、從迴圈的下一次繼續
• pass: 無事
• else: 在迴圈走到底時執行
>>> for n in range(2,10):
... for x in range(2,n):
... if n % x == 0:
... print n, 'equals', x, '*', n/x
... break
... else: # not for "if", but for end-of-for-loop
... print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
6. 迴圈的小技巧
• 翻遍字典: items()
>>> for stuff, price in prices.items():
... print stuff, '的價格是', price
...
orange 的價格是 4.5
apple 的價格是 7.5
banana 的價格是 2
• 列出序列的索引: enumerate() [流水號]
>>> m = prices.keys()
>>> m.sort()
>>> for i, v in enumerate(m):
... print i, v
0 apple
1 banana
2 orange
• 同時 loop 兩個序列: zip()
>>> questions = [ name , quest , favorite color ]
>>> answers = [ lancelot , the holy grail , blue ]
>>> for q, a in zip(questions, answers):
... print What is your %s? It is %s. % (q, a)
...
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.






本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/25176/showart_191325.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP