Python 簡介
出自KMU Wiki
(修訂版本間差異)
在2008年12月10日 (三) 18:39所做的修訂版本 (編輯) Mcdlee (對話 | 貢獻) (→產生個人化訊息) ←上一個 |
當前修訂版本 (2008年12月24日 (三) 19:41) (編輯) (撤銷) 9401144 (對話 | 貢獻) (→隨機抽樣名單) |
||
(10個中途的修訂版本沒有顯示。) | |||
第12行: | 第12行: | ||
2008 年 12 月 3 日 發行 [http://www.python.org/download/releases/3.0/ Python 3.0 版] ([http://docs.python.org/3.0/whatsnew/3.0.html Python 3.0 有何新改變]) | 2008 年 12 月 3 日 發行 [http://www.python.org/download/releases/3.0/ Python 3.0 版] ([http://docs.python.org/3.0/whatsnew/3.0.html Python 3.0 有何新改變]) | ||
+ | |||
+ | ==Python語法== | ||
+ | |||
+ | ==Debug (程式除錯) Python== | ||
+ | |||
+ | 在 Python 原始程式中 import pdb | ||
+ | |||
+ | pdb 的用法和 gdb 很相似 | ||
+ | |||
+ | 詳情參考 [http://www.ferg.org/papers/debugging_in_python.html Debugging in Python] | ||
+ | |||
+ | ==Python 與中文== | ||
==免費電子書== | ==免費電子書== | ||
第25行: | 第37行: | ||
[http://www.python.org/download/ 官方網站下載] | [http://www.python.org/download/ 官方網站下載] | ||
- | [http://ftp.kmu.edu.tw/Win/Python/ 校內下載] | + | [http://ftp.kmu.edu.tw/Win/Python/ 校內下載 (2.6,3.0)] |
==參考資料== | ==參考資料== | ||
第209行: | 第221行: | ||
import string | import string | ||
- | #filename = | + | #filename = raw_input("Please enter the file name.") |
f = file('st.txt') | f = file('st.txt') | ||
第225行: | 第237行: | ||
f.close() | f.close() | ||
- | stid = | + | stid = raw_input("Please enter the ID number") |
if stlist.has_key(stid): | if stlist.has_key(stid): | ||
stname = stlist[stid] | stname = stlist[stid] | ||
print "Dear", stname ,"\n Your e-mail is u",stid,"@kmu.edu.tw" | print "Dear", stname ,"\n Your e-mail is u",stid,"@kmu.edu.tw" | ||
+ | </pre> | ||
+ | |||
+ | ====參考解答jai166==== | ||
+ | <pre> | ||
+ | #!/usr/local/bin/python | ||
+ | # -*- coding: cp950 -*- | ||
+ | import string | ||
+ | def isInt( strInput ): # 判斷參數是否為整數(全為數字) | ||
+ | for i in strInput: | ||
+ | if i<'0' or i>'9': | ||
+ | return 0 | ||
+ | return 1 | ||
+ | |||
+ | class customList: | ||
+ | # 程式的主要核心 | ||
+ | # 內有 dic 用以儲存輸入的資料 學號:姓名 | ||
+ | # 有 Read/Express 處理輸入/輸出的部分,用 Source 選擇資料來源/輸出裝置 | ||
+ | def __init__(self): # 初始化 | ||
+ | self.dic = dict() # 宣告 customList 有個物件 dic 是個 dictionary | ||
+ | self.ioMethod=iomethod() #ioMethod 是個 iomethod 類別的物件 | ||
+ | def Read(self): | ||
+ | self.Source() | ||
+ | self.ioMethod.Read(self.dic) | ||
+ | def Express(self): | ||
+ | self.Source() | ||
+ | self.ioMethod.Express(self.dic) | ||
+ | def Source(self): | ||
+ | print "請問要從哪輸入/輸出? 1.螢幕 2.檔案[1]", | ||
+ | ch = raw_input() | ||
+ | if ch =="2" : | ||
+ | self.ioMethod=iomethodFile() | ||
+ | else : | ||
+ | self.ioMethod=iomethodScreen() | ||
+ | # iomethod 是 iomethodScreen 和 iomethodFile 的原型 | ||
+ | class iomethod: | ||
+ | def express(self,k,v): | ||
+ | print ("親愛的 %s 同學,\n您學校的 e-mail 信箱是 u%s@kmu.edu.tw" % (v , k) ) | ||
+ | def read(self,inData,dic): | ||
+ | if inData == "exit" : return 1 | ||
+ | if inData == "" : return 1 | ||
+ | inData = inData.split(" ",2) | ||
+ | if len(inData)==2 : | ||
+ | if inData[0] in dic: | ||
+ | print "已有資料,是否覆寫?(Y/n)", | ||
+ | ch=raw_input() | ||
+ | if ch == "N" or ch == "n": | ||
+ | return 0 | ||
+ | if isInt(inData[0]): | ||
+ | dic[inData[0]]=inData[1] | ||
+ | else : | ||
+ | print inData[0],inData[1],": ",inData[0],"學號錯誤!!" | ||
+ | else : | ||
+ | for x in inData: | ||
+ | print x, | ||
+ | print ": 輸入錯誤,請重新輸入" | ||
+ | return 0 | ||
+ | def ExpressS(self,dic): | ||
+ | print "1. 依學號輸出結果" | ||
+ | print "2. 輸出全部結果" | ||
+ | print "3. 離開" | ||
+ | print "請選擇您要的選項:", | ||
+ | ch=raw_input(); | ||
+ | if ch =='1' : | ||
+ | self.ExpressOne(dic) | ||
+ | if ch =='2' : | ||
+ | self.ExpressAll(dic) | ||
+ | if ch =='3' : | ||
+ | return | ||
+ | def ExpressOne(self,dic): | ||
+ | while(1): | ||
+ | print "輸入欲查詢之學號,或輸入exit離開:", | ||
+ | ch = raw_input() | ||
+ | if ch == "exit" : break | ||
+ | if ch == "" : break | ||
+ | if ch in dic: | ||
+ | self.express(ch, dic[ch]) | ||
+ | def ExpressAll(self,dic): | ||
+ | for (k, v)in dic.iteritems(): | ||
+ | self.express(k, v) | ||
+ | |||
+ | class iomethodScreen(iomethod): | ||
+ | def Read(self,dic): | ||
+ | while(1): | ||
+ | print "輸入名單:學號 姓名,或打exit離開:", | ||
+ | inData=raw_input(); | ||
+ | if self.read(inData,dic): | ||
+ | break | ||
+ | def Express(self,dic): | ||
+ | self.ExpressS(dic) | ||
+ | |||
+ | class iomethodFile(iomethod): | ||
+ | def Read(self,dic): | ||
+ | try: | ||
+ | self.s=self.Source("r") | ||
+ | while (1): | ||
+ | inData = self.s.readline() | ||
+ | if inData == "": return | ||
+ | inData=inData.partition('\n')[0] | ||
+ | self.read(inData,dic) | ||
+ | s.close() | ||
+ | except IOError: | ||
+ | print "檔案來源錯誤: " | ||
+ | return | ||
+ | def Express(self,dic): | ||
+ | self.s=self.Source("w") | ||
+ | self.ExpressS(dic) | ||
+ | self.s.close() | ||
+ | def express(self,k,v): | ||
+ | self.s.write("親愛的 %s 同學,\n您學校的 e-mail 信箱是 u%s@kmu.edu.tw\n" % (v , k) ) | ||
+ | def Source(self,mode): | ||
+ | if mode == "r": | ||
+ | print "來源檔案是?[data.txt]", | ||
+ | else : | ||
+ | if mode == "w": | ||
+ | print "輸出檔案是?[out.txt]", | ||
+ | else : | ||
+ | pass | ||
+ | name = raw_input() | ||
+ | if name == "": | ||
+ | if mode == "r": | ||
+ | name = "data.txt" | ||
+ | else : | ||
+ | if mode == "w": | ||
+ | name = "out.txt" | ||
+ | f=open(name, mode) | ||
+ | return f | ||
+ | # 程式進入點 | ||
+ | data = customList() | ||
+ | while(1): | ||
+ | print "1. 讀取資料" | ||
+ | print "2. 輸出結果" | ||
+ | print "3. 結束" | ||
+ | print "請選擇您要的選項:", | ||
+ | ch=raw_input() | ||
+ | if ch =='1' : | ||
+ | data.Read() | ||
+ | if ch =='2' : | ||
+ | data.Express() | ||
+ | if ch =='3' : | ||
+ | exit() | ||
+ | |||
+ | </pre> | ||
+ | |||
+ | ===隨機抽樣名單=== | ||
+ | |||
+ | 假設有以下的學號 (五個系所,連號): | ||
+ | |||
+ | 99000001 ~ 99000100 | ||
+ | |||
+ | 99001001 ~ 99001050 | ||
+ | |||
+ | 99002001 ~ 99002064 | ||
+ | |||
+ | 99025001 ~ 99025072 | ||
+ | |||
+ | 99026001 ~ 99026036 | ||
+ | |||
+ | 其中開頭兩碼為入學年,接下來三碼為系所代碼,末三碼為序號, | ||
+ | 請產生一個每班抽樣 10% 的隨機名單。 | ||
+ | |||
+ | ====參考解答jai166==== | ||
+ | <pre> | ||
+ | #!/usr/local/bin/python | ||
+ | # -*- coding: cp950 -*- | ||
+ | import string | ||
+ | import random | ||
+ | import math | ||
+ | import pdb | ||
+ | global lengthClass, lengthStd | ||
+ | lengthClass = 5 | ||
+ | lengthStd = 3 | ||
+ | def randSelect(alln, howmuch): # all: list | ||
+ | results = set() | ||
+ | random.seed() | ||
+ | howmuch=int(howmuch) | ||
+ | if howmuch == 0 : return results | ||
+ | while 1: | ||
+ | temp=int(random.random()*len(alln)) # random() return 0~1 | ||
+ | if int(alln[temp]) in results: | ||
+ | continue | ||
+ | else: | ||
+ | results.add(int(alln[temp])) | ||
+ | if len(results) == howmuch: | ||
+ | return results | ||
+ | |||
+ | def dataInput(database): | ||
+ | print "Please enter student's number, or type 'exit'" | ||
+ | while 1: | ||
+ | ch = raw_input() | ||
+ | if ch == "exit" : return | ||
+ | if ch == "" : return | ||
+ | ch=string.atoi(ch) | ||
+ | classNo = int(ch/(math.pow(10,lengthStd))) | ||
+ | if classNo not in database: | ||
+ | database[classNo]=list() | ||
+ | database[classNo].append(ch) | ||
+ | |||
+ | def dataInput2(database): | ||
+ | print "Please enter the leading ", lengthClass, " characters of student's number, or type 'exit'", | ||
+ | classNo = raw_input() | ||
+ | if ch == "exit" : return | ||
+ | if ch == "" : return | ||
+ | print "How many people in this class??", | ||
+ | ch2 = raw_input() | ||
+ | classNo = int(classNo) | ||
+ | ch2 = int(ch2) | ||
+ | if classNo not in database: | ||
+ | database[classNo]=list() | ||
+ | for i in range(0,ch2): | ||
+ | if classNo*math.pow(10,lengthStd)+i+1 not in database[classNo]: | ||
+ | database[classNo].append(classNo*math.pow(10,lengthStd)+i+1) | ||
+ | |||
+ | def dataOutput(database): | ||
+ | for x in database: | ||
+ | i=0 | ||
+ | for y in randSelect(database[x],len(database[x])/10): | ||
+ | print y, | ||
+ | i=(i+1)%5 | ||
+ | if i!=0: print "", | ||
+ | else : print "" | ||
+ | print "\n" | ||
+ | |||
+ | database = dict() | ||
+ | while 1: | ||
+ | print "1. input by number" | ||
+ | print "2. input by class" | ||
+ | print "3. output" | ||
+ | print "4. exit" | ||
+ | |||
+ | ch = raw_input() | ||
+ | if ch == "1" : dataInput(database) | ||
+ | if ch == "2" : dataInput2(database) | ||
+ | if ch == "3" : dataOutput(database) | ||
+ | if ch == "4" : exit() | ||
</pre> | </pre> |
當前修訂版本
本條目所指的 Python 是 Python 程式語言
目錄 |
[編輯] 概覽
A Byte of Python 對 Python 的簡介(中譯版)
根據 2008 年 11 月 TIOBE Programming Community Index,Python 的普及率在全世界排名第 6
2008 年 12 月 3 日 發行 Python 3.0 版 (Python 3.0 有何新改變)
[編輯] Python語法
[編輯] Debug (程式除錯) Python
在 Python 原始程式中 import pdb
pdb 的用法和 gdb 很相似
詳情參考 Debugging in Python
[編輯] Python 與中文
[編輯] 免費電子書
[編輯] 下載
[編輯] 參考資料
[編輯] 練習
[編輯] 檢查一個數是否為質數
- 題目
由使用者輸入一個整數,然後判斷其是否為質數。
[編輯] 參考解答jai166
import math #!/usr/local/bin/python # -*- coding: cp950 -*- import string def isInt( strInput ): # 判斷參數是否為整數(全為數字) for i in strInput: if i<'0' or i>'9' : if i!='-': # 讓負數也可輸入 return 0 return 1 def isPrime(chkN): if isInt(chkN) : chkN=string.atol(chkN) else: raise ValueError("%s 並不是整數!" %(chkN) ) if chkN == -1: return 1 # -1 是質數(1, -1) if chkN <-1 : return 0 # -2 以下皆不是質數(1, -1, self, ...) if chkN == 0 : return 0 # 任意數*0 = 0 if chkN == 1 : return 0 # 1 不是質數 if chkN == 2 : return 1 # 2 唯一的偶數質數 if ( chkN % 2 )==0 : return 0 # 其他偶數皆不是質數 sun=3 # 從3 開始的質數測,不測偶數 end=math.floor(math.sqrt(chkN))+1 # 測到自己開根號 while sun < end: if ( chkN % sun )==0: # 整除 return 0 sun+=2 return 1 # 程式進入點 while(1): try: print "請輸入一個數以檢查它是否為質數, 要離開請打 exit", input = raw_input() if input == "" or input == "exit" : exit() if isPrime(input) : print input, "是個質數" else: print input, "不是!!" except ValueError, err: print err print "輸入錯誤,請重打一遍"
[編輯] 參考解答mcdlee
#!/usr/bin/env python import math import time x = int(raw_input("enter a number\n")) start = time.clock() a = 2 prime = [2] def say_yes(): print a, 'is a prime number' while a <= x: if a in prime: say_yes() for item in prime: b = a % item if b == 0: break else: say_yes() prime.append(a) a = a + 1 amount = len(prime) print 'There is', amount, 'prime number below', x
[編輯] 參考解答sevenstar
[編輯] 參考解答cch
#!/usr/local/bin/python # This program tests wether an integer is a prime import sys import math import string print 'This program tests wether an integer is a prime' while 1 : sys.stdout.write('Please input an integer: ') s = raw_input() n = string.atol(s) ub = math.sqrt(n) + 1 is_prime = 1 f = 2 while f < ub : if n % f == 0: is_prime = 0 print n, ' has a factor ', f break else : f = f + 1 if is_prime == 1 : print n, ' is a prime' else : print n, ' is not a prime'
附註:
- FreeBSD 上有一支程式 primes (/usr/games/primes) 可幫我們列出質數以供測試,如: primes 100 200 可列出 100 到 200 間的質數
- 根據 維基百科英文版對質數的介紹,有一個 polynomial time 的演算法 AKS
[編輯] 產生個人化訊息
- 題目
假設今天有一個名單(固定)如下:
99001001 趙一忠 99001024 錢二孝 99002015 孫三仁 99051273 李四愛 99181730 周五信
我們需要通知其中若干位同學,只知道他們的學號,請寫一支程式產生如下訊息:
親愛的 {姓名} 同學, 您學校的 e-mail 信箱是 u{學號}@kmu.edu.tw
[編輯] 參考解答cch
#!/usr/local/bin/python import string st = {} f = file('st.txt') while True: line = f.readline() if len(line) == 0: break line.rstrip() e = string.split(line, ' ') st[e[0]] = e[1] f.close() # for sno, name in st.items() : # print "sno = %s name = %s" % (sno, name) print 'Please input a sno ', s = raw_input(); print 'Dear %s,\n Your e-mail is u%s@kmu.edu.tw' % (st[s], s)
[編輯] 參考解答mcdlee
#!/usr/bin/env python import string #filename = raw_input("Please enter the file name.") f = file('st.txt') stlist = {} #create a new dictionary while True: line = f.readline() if len(line) == 0: break line.strip() e = string.split(line, ' ') if len(e) == 2: stlist[e[0]] = e[1] print stlist.keys() f.close() stid = raw_input("Please enter the ID number") if stlist.has_key(stid): stname = stlist[stid] print "Dear", stname ,"\n Your e-mail is u",stid,"@kmu.edu.tw"
[編輯] 參考解答jai166
#!/usr/local/bin/python # -*- coding: cp950 -*- import string def isInt( strInput ): # 判斷參數是否為整數(全為數字) for i in strInput: if i<'0' or i>'9': return 0 return 1 class customList: # 程式的主要核心 # 內有 dic 用以儲存輸入的資料 學號:姓名 # 有 Read/Express 處理輸入/輸出的部分,用 Source 選擇資料來源/輸出裝置 def __init__(self): # 初始化 self.dic = dict() # 宣告 customList 有個物件 dic 是個 dictionary self.ioMethod=iomethod() #ioMethod 是個 iomethod 類別的物件 def Read(self): self.Source() self.ioMethod.Read(self.dic) def Express(self): self.Source() self.ioMethod.Express(self.dic) def Source(self): print "請問要從哪輸入/輸出? 1.螢幕 2.檔案[1]", ch = raw_input() if ch =="2" : self.ioMethod=iomethodFile() else : self.ioMethod=iomethodScreen() # iomethod 是 iomethodScreen 和 iomethodFile 的原型 class iomethod: def express(self,k,v): print ("親愛的 %s 同學,\n您學校的 e-mail 信箱是 u%s@kmu.edu.tw" % (v , k) ) def read(self,inData,dic): if inData == "exit" : return 1 if inData == "" : return 1 inData = inData.split(" ",2) if len(inData)==2 : if inData[0] in dic: print "已有資料,是否覆寫?(Y/n)", ch=raw_input() if ch == "N" or ch == "n": return 0 if isInt(inData[0]): dic[inData[0]]=inData[1] else : print inData[0],inData[1],": ",inData[0],"學號錯誤!!" else : for x in inData: print x, print ": 輸入錯誤,請重新輸入" return 0 def ExpressS(self,dic): print "1. 依學號輸出結果" print "2. 輸出全部結果" print "3. 離開" print "請選擇您要的選項:", ch=raw_input(); if ch =='1' : self.ExpressOne(dic) if ch =='2' : self.ExpressAll(dic) if ch =='3' : return def ExpressOne(self,dic): while(1): print "輸入欲查詢之學號,或輸入exit離開:", ch = raw_input() if ch == "exit" : break if ch == "" : break if ch in dic: self.express(ch, dic[ch]) def ExpressAll(self,dic): for (k, v)in dic.iteritems(): self.express(k, v) class iomethodScreen(iomethod): def Read(self,dic): while(1): print "輸入名單:學號 姓名,或打exit離開:", inData=raw_input(); if self.read(inData,dic): break def Express(self,dic): self.ExpressS(dic) class iomethodFile(iomethod): def Read(self,dic): try: self.s=self.Source("r") while (1): inData = self.s.readline() if inData == "": return inData=inData.partition('\n')[0] self.read(inData,dic) s.close() except IOError: print "檔案來源錯誤: " return def Express(self,dic): self.s=self.Source("w") self.ExpressS(dic) self.s.close() def express(self,k,v): self.s.write("親愛的 %s 同學,\n您學校的 e-mail 信箱是 u%s@kmu.edu.tw\n" % (v , k) ) def Source(self,mode): if mode == "r": print "來源檔案是?[data.txt]", else : if mode == "w": print "輸出檔案是?[out.txt]", else : pass name = raw_input() if name == "": if mode == "r": name = "data.txt" else : if mode == "w": name = "out.txt" f=open(name, mode) return f # 程式進入點 data = customList() while(1): print "1. 讀取資料" print "2. 輸出結果" print "3. 結束" print "請選擇您要的選項:", ch=raw_input() if ch =='1' : data.Read() if ch =='2' : data.Express() if ch =='3' : exit()
[編輯] 隨機抽樣名單
假設有以下的學號 (五個系所,連號):
99000001 ~ 99000100
99001001 ~ 99001050
99002001 ~ 99002064
99025001 ~ 99025072
99026001 ~ 99026036
其中開頭兩碼為入學年,接下來三碼為系所代碼,末三碼為序號, 請產生一個每班抽樣 10% 的隨機名單。
[編輯] 參考解答jai166
#!/usr/local/bin/python # -*- coding: cp950 -*- import string import random import math import pdb global lengthClass, lengthStd lengthClass = 5 lengthStd = 3 def randSelect(alln, howmuch): # all: list results = set() random.seed() howmuch=int(howmuch) if howmuch == 0 : return results while 1: temp=int(random.random()*len(alln)) # random() return 0~1 if int(alln[temp]) in results: continue else: results.add(int(alln[temp])) if len(results) == howmuch: return results def dataInput(database): print "Please enter student's number, or type 'exit'" while 1: ch = raw_input() if ch == "exit" : return if ch == "" : return ch=string.atoi(ch) classNo = int(ch/(math.pow(10,lengthStd))) if classNo not in database: database[classNo]=list() database[classNo].append(ch) def dataInput2(database): print "Please enter the leading ", lengthClass, " characters of student's number, or type 'exit'", classNo = raw_input() if ch == "exit" : return if ch == "" : return print "How many people in this class??", ch2 = raw_input() classNo = int(classNo) ch2 = int(ch2) if classNo not in database: database[classNo]=list() for i in range(0,ch2): if classNo*math.pow(10,lengthStd)+i+1 not in database[classNo]: database[classNo].append(classNo*math.pow(10,lengthStd)+i+1) def dataOutput(database): for x in database: i=0 for y in randSelect(database[x],len(database[x])/10): print y, i=(i+1)%5 if i!=0: print "", else : print "" print "\n" database = dict() while 1: print "1. input by number" print "2. input by class" print "3. output" print "4. exit" ch = raw_input() if ch == "1" : dataInput(database) if ch == "2" : dataInput2(database) if ch == "3" : dataOutput(database) if ch == "4" : exit()