作者ming1053 (ming)
看板b97902HW
標題[計概] Python 入門
時間Mon Nov 3 21:50:25 2008
相信有上今天的計概的各位單班同學都開始接觸 Python 了,TA 在 lab 快速 view 過
一堆語法和 sample code ,如果有當場記起來的那真的是非常厲害,不過搞不太清楚的同
學也不要太擔心,我今天找到一份還算可以的入門放在這裡,除了課程網上公佈的 slide
以外,也可以參考一下這份教學,其實語法和 C 比起來應該是和善多了啦XD 用相同的觀
念應該很容易可以把作業解決的。
另外建議大家可以開始養成查官方 library & document 的習慣了,這對學習一種新的語
言有很大的幫助。
The Python Standard Library
http://docs.python.org/library/
Python Libray Reference
http://www.python.org/doc/2.5.2/lib/lib.html
Python Taiwan
http://www.python.tw/
Python Tutorial
Chinese
http://www.freebsd.org.hk/html/python/tut_tw/tut.html
Origin
http://www.python.org/doc/2.5.2/tut/tut.html
------------------------------------------------------------------------------
使用Python
* 有兩種主要使用python的方法
o 使用互動式命令列
+ e.q. 直接鍵入python就會進入python的互動式命令列
o 將程式寫成檔案,再由python執行
+ 直在將程式碼寫在檔案內,然後再執行python去讀取該檔案
# Ex: python hello.py
+ 或是在檔案的第一個行寫著 #!/usr/bin/env python,然後在第二行
\
之後輸入程式碼,如此可以直接執行該檔案
# Ex: ./hello.py
* 作業平台
o Linux、FreeBSD …
o Windows
第一個python程式 - Hello World
* 使用互動式命令列
>>> print “Hello World”
>>>
* 放在檔案裡
#!/usr/bin/env python
print “Hello World”
基本概念
* 語法特色
o 以冒號(:)做為敘述的開始
o 不必使用分號(;)做為結尾
o 井字號(#)做為註解符號,同行井字號後的任何字將被忽略
o 使用tab鍵做為縮排區塊的依據
o 不必指定變數型態 (runtime時才會進行binding)
變數(Variables)和 表示式(Expressions)
* 表示式
3 + 5
3 + (5 * 4)
3 ** 2
‘Hello’ + ‘World’
* 變數指定
a = 4 << 3
b = a * 4.5
c = (a+b)/2.5
a = “Hello World”
o 型別是動態的,會根據指定時的物件來決定型別
o 變數單純只是物件的名稱,並不會和記憶體綁在一起。
e.q.和記憶體綁在一起的是物件,而不是物件名稱。
條件式敘述
(Conditional Statements) Part I
* if-else
if a < b:
z = b
else:
z = a
* pass 敘述 - 不做任何事時使用
if a < b:
pass
else:
z = a
條件式敘述
(Conditional Statements) Part II
* elif敘述
if a == ‘+’:
op = PLUS
elif a == ‘-’:
op = MINUS
else:
op = UNKNOWN
o 沒有像C語言一樣,有switch的語法
* 布林表示式 - and, or, not
if b >= a and b <= c:
print ‘b is between a and c’
if not (b < a or c > c):
print ‘b is still between a and c’
基本型態 (Numbers and String)
* Numbers (數)
a = 3 # Integer (整數)
b = 4.5 # Float point (浮點數)
c = 51728888333L # Long Integer (精準度無限)
d = 4 + 3j # Complex number (複數)
* Strings (字串)
a = 'Hello' # Single quotes
b = 'World' # Double quotes
c = "Bob said 'hey there.'" # A mix of both
d = '''A triple qouted string
can span multiple lines
like this'''
e = """Also works for double quotes"""
基本型態 - 串列(Lists)
* 任意物件的串列
a = [2, 3, 4] # A list of integer
b = [2, 7, 3.5, “Hello”] # A mixed list
c = [] # An empty list
d = [2, [a, b]] # A list containing a list
e = a + b # Join two lists
* 串列的操作
x = a[1] # Get 2nd element (0 is first)
y = b[1:3] # Return a sub-list
z = d[1][0][2] # Nested lists
b[0] = 42 # Change an element
基本型態 - 固定有序列(Tuples)
* Tuples
f = (2,3,4,5) # A tuple of integers
g = (,) # An empty tuple
h = (2, [3,4], (10,11,12)) # A tuple containing mixed objects
* Tuples的操作
x = f[1] # Element access. x = 3
y = f[1:3] # Slices. y = (3,4)
z = h[1][1] # Nesting. z = 4
* 特色
o 與list類似,最大的不同tuple是一種唯讀且不可變更的資料結構
o 不可取代tuple中的任意一個元素,因為它是唯讀不可變更的
基本型態 - 字典 (Dictionaries)
* Dictionaries (關聯陣列)
a = { } # An empty dictionary
b = { ’x’: 3, ’y’: 4 }
c = { ’uid’: 105,
’login’: ’beazley’,
’name’ : ’David Beazley’
}
* Dictionaries的存取
u = c[’uid’] # Get an element
c[’shell’] = "/bin/sh" # Set an element
if c.has_key("directory"): # Check for presence of an member
d = c[’directory’]
else:
d = None
d = c.get("directory",None) # Same thing, more compact
迴圈 (Loops)
* while敘述
while a < b:
# Do something
a = a + 1
* for敘述 (走訪序列的元素)
for i in [3, 4, 10, 25]:
print i
# Print characters one at a time
for c in "Hello World":
print c
# Loop over a range of numbers
for i in range(0,100):
print i
函式 (Functions)
* def敘述
# Return the remainder of a/b
def remainder(a,b):
q = a/b
r = a - q*b
return r
# Now use it
a = remainder(42,5) # a = 2
* 回傳一個以上的值
def divide(a,b):
q = a/b
r = a - q*b
return q,r
x,y = divide(42,5) # x = 8, y = 2
類別 (Classes)
* class敘述
class Account:
def __init__(self, initial):
self.balance = initial
def deposit(self, amt):
self.balance = self.balance + amt
def withdraw(self,amt):
self.balance = self.balance - amt
def getbalance(self):
return self.balance
* 使用定義好的class
a = Account(1000.00)
a.deposit(550.23)
a.deposit(100)
a.withdraw(50)
print a.getbalance()
例外處理 (Exceptions)
* try敘述
try:
f = open("foo")
except IOError:
print "Couldn’t open ’foo’. Sorry."
* raise敘述
def factorial(n):
if n < 0:
raise ValueError,"Expected non-negative number"
if (n <= 1): return 1
else: return n*factorial(n-1)
* 沒有處理的例外
>>> factorial(-1)
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in factorial
ValueError: Expected non-negative number
>>>
檔案處理
* open()函式
f = open("foo","w") # Open a file for writing
g = open("bar","r") # Open a file for reading
* 檔案的讀取/寫入
f.write("Hello World")
data = g.read() # Read all data
line = g.readline() # Read a single line
lines = g.readlines() # Read data as a list of lines
* 格式化的輸入輸出
o 使用%來格式化字串
for i in range(0,10):
f.write("2 times %d = %d\n" % (i, 2*i))
模組 (Modules)
* 程式可分成好幾個模組
# numbers.py
def divide(a,b):
q = a/b
r = a - q*b
return q,r
def gcd(x,y):
g = y
while x > 0:
g = x
x = y % x
y = g
return g
* import敘述
import numbers
x,y = numbers.divide(42,5)
n = numbers.gcd(7291823, 5683)
Python的標準模組函式庫
* Python本身就包含了大量的模組提供使用
o String processing
o Operating system interfaces
o Networking
o Threads
o GUI
o Database
o Language services
o Security.
* 使用模組
import string
...
a = string.split(x)
原文轉載自
http://www.cdpa.nsysu.edu.tw/wp/wp-content/uploads/2006/07/Python.ppt
--
◢◢◢
▃▃ ▃▂
◢
▃▂
▂┐ ▃ ▂▂▂▃
▆◤◤ ▎
◤▎
◥ ◤◢ │ φ批踢踢兔.itsming
▂▂▂
▄▎
▄▎
◣ ▊◣ └ ▁▁▁▁▁▁▁▁▁
▌▌▌ ▎ ▎
◣◥▎ ┌ ──── ▅▅ ◤
◤◤◤ ▅▅ ▅▅▅▅ ▇▅▆ ▅
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.239.158
推 benck:好長= = 不過還是先推1個 11/03 21:51
推 fishead1116:原po超認真 幫推一個 11/03 23:17
推 Poplarysl: 幫推 照顧長帳號~~ 11/04 00:05
※ 編輯: ming1053 來自: 140.112.239.158 (11/04 00:47)
→ chenaren:糟糕 不應該貪睡的 11/05 00:13
推 dennis2030:請問 b = 'World' # Double quotes ' 要改成 " 嗎? 11/06 14:29
推 jimmyken793:印象中前後一樣就可以 11/06 21:14
推 dennis2030:所以那句的意思是 不管'或是"都是指定成字串? 11/07 00:27
→ dennis2030:話說忘了感謝ming同學努力的幫忙蒐集資料!感謝! 11/07 00:28
推 jimmyken793:對 但是引號要成對 也就是說'' 或 "" 11/07 00:55