1 | # -*- coding: UTF-8 -*- |
上例將檔案編碼宣告成 UTF-8 編碼,支援許多非英語系國家的文字符號,包括中、日、韓等語文。
Python 3 之後的版本直接支援 Unicode 編碼,這是說,程式檔案必須以 Unicode 編碼儲存,同時除了關鍵字 (keyword) 及內建名稱外,識別字 (identifier) 皆可使用 Unicode 編碼的符號,也就是說,可以直接用中文當變數 (variable) 名稱。
如下例,程式利用 random 模組 (module) 中的 randint() 函數 (function) 隨機取得 1 到 10 之間的一個數字當「答案」,然後程式自己「猜測」,直到「答案」與「猜測」相符,結果便顯示總共的猜測「計數」
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import random 答案 = random.randint( 1 , 10 ) 猜測 = 0 計數 = 0 print ( "所要猜的數字是" , 答案) while 答案 ! = 猜測: print ( "猜錯了,再猜一次 :)" ) 猜測 = random.randint( 1 , 10 ) 計數 + = 1 print ( "猜對囉!一共猜了" , 計數, "次" ) # 《程式語言教學誌》的範例程式 # 檔名:hello.py # 功能:示範 Python 程式 # 作者:張凱慶 # 時間:西元 2010 年 11 月 */ |
執行結果如下

第 5 行到第 7 行
5 6 7 | 答案 = random.randint( 1 , 10 ) 猜測 = 0 計數 = 0 |
答案、猜測、計數三者為在此例中自行命名的識別字,也就是變數,這裡使用的是中文。
第 1 行的 import
1 | import random |
與第 8 行的 while
8 | while 答案 ! = 猜測: |
import 用來引入標準模組庫 (standard library) 中的模組, while 用於迴圈 (loop) ,這兩者都是關鍵字之一。
此外,程式中重複出現的
random.randint( 1 , 10 ) |
以及
print ( "所要猜的數字是" , 答案) print ( "猜錯了,再猜一次 :)" ) print ( "猜對囉!一共猜了" , 計數, "次" ) |
randint 與 print 為內建名稱,此二者皆為函數,後頭小括弧為放置參數 (parameter) 的地方。
注意到這裡,關鍵字與內建名稱仍是英文。雖然 Python 3 可以直接運用中文寫程式,也可以直接有效的處理中文資料,但我們仍會以英文作為程式示範之用,包括識別字與字串 (string) 內容。
中英文術語對照 | |
---|---|
關鍵字 | keyword |
識別字 | identifier |
變數 | variable |
模組 | module |
函數 | function |
標準模組庫 | standard library |
迴圈 | loop |
參數 | parameter |
字串 | string |
參考資料
http://docs.python.org/py3k/reference/lexical_analysis.html
http://www.python.org/dev/peps/pep-3131/
http://www.python.org/dev/peps/pep-0263/
http://docs.python.org/py3k/reference/lexical_analysis.html
http://www.python.org/dev/peps/pep-3131/
http://www.python.org/dev/peps/pep-0263/
1 則留言:
Great! Thank you.
張貼留言