自由軟體工作坊  - Python  入門 Python tutorial Lloyd Huang [email_address]
簡介: Python  是一種泛用性的動態物件導向程式語言。自  1990  年代初由  Guido van Rossum  ( 又常被稱為  GvR  或  BDFL)  創造至今已歷十數年發展,應用於系統管理、網路管理、網路傳輸程式、網頁程式開發、數值分析程式、圖形介面應用程式等方面,均有優秀的表現。 本課程將會介紹這個程式語言的特性,以及目前廣為應用的部份。附帶簡短的實作教學,藉此一窺  Python  的能力,並提供一個學習的入門階。
今日內容: 初學  Python 型別  Types ,運算  Operators 語法  Statements 函數  Functions 模組  Modules 物件  Classes 例外處理  Exceptions 常用  Python Modules Python Web CGI howto
Python  是什麼? 1990 年代初由  Guido  開發的程式語言 泛用性的動態物件導向程式語言 應用於系統管理 網路管理 網路傳輸程式 網頁程式開發 數值分析程式 圖形介面應用程式
誰在用  Python ? Google Youtube BitTorrent NASA OLPC Plurk
Python  特色 ? 方便的  Python 快速的  Python 跨平台的  Python 高彈性的  Python
Python  語言特性 ? Script  特性 語法強迫縮排 直譯器 動態語言特性 物件導向 跨平台 Python program is Python module Duck type 豐富的線上說明跟手冊
一分鐘學  python import os def do_func(): mylst=['hello','world',2,'python!'] for x in mylst: print x, a='ls -al' if a=='ls -al': do_func() os.system(a)
 
30 分鐘學  python Interpreter Python String Slices List Slices advanced for loop while loop def function (): help(), dir(),type()
六小時學  python ? 你等一下就會知道了
日本 Ruby 會長高橋征義說 輕量之人 怠惰 勤勉之人 多數派  -  努力工作 勤勉之人用的語言 Cobol C/C++ java 程式設計師在 日本 有兩類 輕量之人用的語言 Ruby Perl Python 勤勉之人 寫很多程式碼 一個方法  1000  行 輕量之人 1000 方法一行
可讀性語言  VS  唯寫性語言 #!/bin/sh # t2h {$1} html-ize a text file and save as foo.htm NL=&quot; &quot; cat $1 \ | sed -e 's/ at / at /g' \ | sed -e 's/[[:cntrl:]]/ /g'\ | sed -e 's/^[[:space:]]*$//g' \ | sed -e '/^$/{'&quot;$NL&quot;'N'&quot;$NL&quot;'/^\n$/D'&quot;$NL&quot;'}' \ | sed -e 's/^$/<\/UL><P>/g' \ | sed -e '/<P>$/{'&quot;$NL&quot;'N'&quot;$NL&quot;'s/\n//'&quot;$NL&quot;'}'\ | sed -e 's/<P>[[:space:]]*&quot;/<P><UL>&quot;/' \ | sed -e 's/^[[:space:]]*-/<BR> -/g' \ | sed -e 's/http:\/\/[[:graph:]\.\/]*/<A HREF=&quot;&&quot;>[&]<\/A> /g'\ > foo.htm
可讀性語言  VS  唯寫性語言 echo -e &quot;192.168.1.243 1000 T\n 192.168.1.243 1001 T \n 192.168.1.243 1002 L&quot;  | sed 's/\(100\)\(.\)/\1\20/' echo '&#228;&#184;&#173;&#230;&#150;&#135;' |perl -p -e 's/&#(\d+);/chr($1)/eg'
一分鐘學  python import os def do_func(): mylst=['hello','world',2,'python!'] for x in mylst: print x, a='ls -al' if a=='ls -al': do_func() os.system(a)
行前叮嚀
初學  Python 下載 & 安裝 & 移除 google -> python download http://www.python.org/download/ 直譯器的使用 hello world python Python  教學文件 http://tinyurl.com/jubwx Python  學習手冊 http://tinyurl.com/c9ga73
型別  Types ,運算  Operators 數字  Numbers python  計算機 >>> a = 5 >>> a + 1 >>> a + _ >>> a + _ >>> a / 3 ; a / 3.0 字串  String  +---+---+---+---+---+  | H | e | l | p | A | +---+---+---+---+---+  0  1  2  3  4  5  -5  -4  -3  -2  -1 >>> stra='abc ' >>> stra + stra >>> stra * 3
型別  Types ,運算  Operators 列  List a=['a','b','c','d','e'] b=[1,2,3,4,5,6,'abc'] c=[a,b,a,b] len(c) ; len(a) ; len(b) 字典  Dict tel = {'jack': 4098, 'sape': 4139} tel['guido'] = 4127 del tel['sape'] tel['irv'] = 4127 tel tel.keys() tel.keys()[1] tel.has_key('guido')
語法  Statements - if else if elif else >>> x = int(raw_input(&quot;Please enter a number: &quot;)) >>> if x < 0: ...  x = 0 ...  print 'Negative changed to zero' ... elif x == 0: ...  print 'Zero' ... elif x == 1: ...  print 'Single' ... else: ...  print 'More' ...
語法  Statements - while while loop >>> a, b = 0, 1 >>> while b < 1000: ...  print b, ...  a, b = b, a+b ...  1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
語法  Statements - for loop for loop >>> a = ['cat', 'window', 'defenestrate'] >>> for x in a: ...  print x, len(x) ...  cat 3 window 6 defenestrate 12
語法  Statements  -  for range for range() >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70] >>> for i in range(1,10): ... print i, 1 2 3 4 5 6 7 8 9 >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ...  print i, a[i], &quot;|&quot;, 0 Mary | 1 had | 2 a | 3 little | 4 lamb |
小試身手 99  乘法表 1x1=1 1x2=2 1x3=3..... 1x9=9 ..... 9x1=9 9x2=18 9x3=27 ... 9x9=81 提示 2  個  for  回圈 range(1,10) print &quot;xxx %d&quot;
函數  Functions def function(): >>> def fib(n):  ...  &quot;Print a Fibonacci series up to n&quot; ...  a, b = 0, 1 ...  while b < n: ...  print b, ...  a, b = b, a+b ... >>> fib(200) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
函數  Functions (n,m=0) def function(n,m=0): >>> def fib(n,m=0):  ...  &quot;Print a Fibonacci series up to n&quot; ...  a, b = 0, 1 ...  while b < n: ...  if m < b: ...  print b, ...  a, b = b, a+b >>> fib(200) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 >>> fib(200,8) >>> fib(m=10,n=200)
函數  Functions  default value def function(): default value def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while 1: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return 1 if ok in ('n', 'no', 'nop', 'nope'): return 0 retries = retries - 1 if retries < 0: raise IOError, 'refusenik user' print complaint >>> ask_ok('Do you really want to quit?') >>> ask_ok('OK to overwrite the file?', 2)
函數  Functions   default value def function(): default value def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while 1: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return 1 if ok in ('n', 'no', 'nop', 'nope'): return 0 retries = retries - 1 if retries < 0: raise IOError, 'refusenik user' print complaint >>> ask_ok('Do you really want to quit?') >>> ask_ok('OK to overwrite the file?', 2)
函數   Functions  return list def function(): return >>> def fib2(n): ...  result = [] ...  a, b = 0, 1 ...  while b < n: ...  result.append(b) ...  a, b = b, a+b ...  return result ...  >>> f100 = fib2(100)  # call it >>> f100  # write the result [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
函數   Functions  return value def function(): return >>> def fib2(n,m): ...  result = [] ...  a, b = 0, 1 ...  while b < n: ...  result.append(b) ...  a, b = b, a+b ...  return result[-m:]  ... >>> a , b = fib2(100,2) >>> print &quot;a=%d b=%d&quot; % (a,b) a=55 b=89
模組   Modules -  Python modules Namespaces are one honking great idea -- let's do more of those! (Zen of Python) split your program into several files for easier maintenance . A module is just a python script with a .py suffix. Syntax: import modulename Your python script is already a module.
模組   Modules -  fibo.py def fib(n): &quot;write Fibonacci series up to n. hi This fib help menu&quot; a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): &quot;&quot;&quot; return Fibonacci series up to n hi This fib2 help menu &quot;&quot;&quot; a, b = 0, 1 result = [] while b < n: result.append(b); a, b = b, a+b return result if __name__ == '__main__': fib(100) f100=fib2(100) print f100
模組   Modules >>> import fibo >>> fibo.fib(1000) >>> fibo.fib2(1000) >>> fib=fibo.fib >>> fib(500) >>> fib2=fibo2.fib >>> fib2(500) >>> from fibo import fib, fib2 >>> fib(500) >>> fib2(500)
模組   Modules dir() help() >>> import fibo, sys >>> dir (fibo) >>> dir (fibo.fib) >>> dir (fibo.fib2) >>> help (fibo) >>> help (fib) >>> help (fib2) >>> dir (sys) >>> help (sys)
Python Modules HOWTO 寫個  modules  感受一下
物件   Classes class FClass: def setdata(self, value): self.data = value def display(self): print self.data x=FClass() y=FClass() x.setdata(&quot;hi all&quot;) y.setdata(7654321) x.display() y.display() x.data=&quot;rewrite data&quot; x.display()
物件   Classes class SClass(FClass): def display(self): print 'SClass value display %s' % self.data z=SClass() z.setdata(42) z.display() x.display()
物件   Classes class TClass(SClass): def __init__(self, value): self.data = value def __add__(self, other): return TClass(self.data + other) def __mul__(self, other): self.data = self.data * other a=TClass(&quot;abc &quot;) a.display() b = a + &quot;xyz&quot; b.display() a * 3 a.display()
例外處理  Exceptions except  (TypeError,someError) : try: try_something() except: do_otherthing() else: do_closing() finally: try: try_something() finally: do_final()
例外處理   Exceptions #!/usr/bin/python while 1: try: x = int(raw_input(&quot;Please enter a number: &quot;)) break except ValueError: print &quot;Oops! That was no valid number.  Try again...&quot; print &quot;You input number is %d&quot; % (x)
例外處理   Exceptions >>> try: ...  raise KeyboardInterrupt ... finally: ...  print 'Goodbye, world!' ...  Goodbye, world! Traceback (innermost last): File &quot;<stdin>&quot;, line 2 KeyboardInterrupt
常用   Python Modules import os import re import string import time import sys import cgi import cgitb import urllib import telnetlib import ftplib
Lots of Python Modules….. Standard Python Modules http://www.python.org/doc/current/modindex.html PyPI:the Python Package Index: third-party Python packages. http://www.python.org/pypi
Python Web CGI howto CGI cgi-test.py #!/usr/bin/python import cgi, string, re, os, sys, time CGI_HTMLHEAD=&quot;Content-type: text/html\n\n&quot; print CGI_HTMLHEAD print &quot;<h3>&quot; print time.ctime() print &quot;</h3>&quot;
Python Web CGI howto HTML setup.html DNS1 Server: <input type=&quot;text&quot; id=&quot;dns1&quot; name=&quot;dns1&quot;/> <input type=&quot;submit&quot; name=&quot;OK&quot; value=&quot; 確定 &quot; /> CGI setup.py import cgi, string, re, os, sys, time CGI_HTMLHEAD=&quot;Content-type: text/html\n\n&quot; print CGI_HTMLHEAD form = cgi.FieldStorage() if form.has_key('OK'): print &quot;<h1>&quot; print &quot;%s&quot; % (form['dns1'].value) print &quot;</h1>&quot;
其他線上文件 For beginer: http://wiki.python.org.tw/ThinkLikeComputerScientist http://wiki.python.org/moin/BeginnersGuide/NonProgrammers For experienced programmer: http://docs.python.org/tut/tut.html http://www.diveintopython.org/ http://wiki.python.org/moin/BeginnersGuide/Programmers Books for python: http://wiki.python.org/moin/PythonBooks
用屠宰場殺豬的方式煎雞蛋
Zen of Python python –c “import this” Simple is better than complex. (C++) Complex is better than complicated. (Java) Readability counts. (Perl) If the implementation is hard to explain, it's a bad idea. (Java framework like EJB) Explicit is better than implicit. (ruby on rails?) There should be one-- and preferably only one --obvious way to do it.
新手 :  你怎麼飛的 ??? 答 : import antigravity
謝謝收看 by Lloyd@ZZZzzz...

More Related Content

PPT
C程式-函式與巨集
PPT
C程式-陣列與指標
PDF
Vim Hacks
PPT
第4章函数
PPTX
Python 入門
PDF
[COSCUP2013] Python, F#, Golang and Friends
PDF
Pycontw2013x
PPT
第5章数组
C程式-函式與巨集
C程式-陣列與指標
Vim Hacks
第4章函数
Python 入門
[COSCUP2013] Python, F#, Golang and Friends
Pycontw2013x
第5章数组

What's hot (14)

PDF
Perl 6 news at 2010-06
PDF
竞赛中C++语言拾遗
PPT
Javascript Training
PPT
2009 CSBB LAB 新生訓練
PDF
LazyRecord: The Fast ORM for PHP
PDF
Learning python in the motion picture industry by will zhou
PDF
Ptyhon 教學 001 程式流程控制(if-elif-else)
PDF
Python basic - v01
PDF
JavaScript现代化排错实践
PDF
论 Python 与设计模式。
PDF
Python学习笔记
PPT
17第十七讲(第七章中)(2)
PPT
页游开发中的 Python 组件与模式
PDF
Python變數與資料運算
Perl 6 news at 2010-06
竞赛中C++语言拾遗
Javascript Training
2009 CSBB LAB 新生訓練
LazyRecord: The Fast ORM for PHP
Learning python in the motion picture industry by will zhou
Ptyhon 教學 001 程式流程控制(if-elif-else)
Python basic - v01
JavaScript现代化排错实践
论 Python 与设计模式。
Python学习笔记
17第十七讲(第七章中)(2)
页游开发中的 Python 组件与模式
Python變數與資料運算
Ad

Viewers also liked (7)

PPTX
TCP/IP通訊協定
PPS
茶餘飯後
PDF
我與編輯器
PDF
數學軟體應用課程 00 - 課程介紹
PDF
106學測數學科參考答案
PDF
臺灣高中數學講義 - 第一冊 - 數與式
PDF
106學測數學試卷
TCP/IP通訊協定
茶餘飯後
我與編輯器
數學軟體應用課程 00 - 課程介紹
106學測數學科參考答案
臺灣高中數學講義 - 第一冊 - 數與式
106學測數學試卷
Ad

Similar to Op 20090411 (20)

PDF
Python 2 - 快速簡介
PPTX
Python攻略
PPT
Python Basic
PDF
PDF
Python基本資料運算
PDF
Programming python - part 1
PPTX
Y3CDS - Python class 01
PDF
Python 工作坊 (NCTU)
PPTX
Python入門:5大概念初心者必備 2021/11/18
PDF
Ch9 教學
PDF
PDF
Ch10 教學
PDF
投影片
PPTX
python基礎教學
PDF
Python 自然語言處理應用 - 1. 環境配置篇 - 2024 / Environment Configuration
PPTX
[3]投影片 futurewad樹莓派研習會 141204
PPTX
ncuma_型別與迴圈.pptx
PPT
Python story
PDF
第一次程式設計就上手 - 使用Python 與周蟒(zhpy)
PPTX
TQC+ 程式語言 Python 05:函式
Python 2 - 快速簡介
Python攻略
Python Basic
Python基本資料運算
Programming python - part 1
Y3CDS - Python class 01
Python 工作坊 (NCTU)
Python入門:5大概念初心者必備 2021/11/18
Ch9 教學
Ch10 教學
投影片
python基礎教學
Python 自然語言處理應用 - 1. 環境配置篇 - 2024 / Environment Configuration
[3]投影片 futurewad樹莓派研習會 141204
ncuma_型別與迴圈.pptx
Python story
第一次程式設計就上手 - 使用Python 與周蟒(zhpy)
TQC+ 程式語言 Python 05:函式

Op 20090411

  • 1. 自由軟體工作坊 - Python 入門 Python tutorial Lloyd Huang [email_address]
  • 2. 簡介: Python 是一種泛用性的動態物件導向程式語言。自 1990 年代初由 Guido van Rossum ( 又常被稱為 GvR 或 BDFL) 創造至今已歷十數年發展,應用於系統管理、網路管理、網路傳輸程式、網頁程式開發、數值分析程式、圖形介面應用程式等方面,均有優秀的表現。 本課程將會介紹這個程式語言的特性,以及目前廣為應用的部份。附帶簡短的實作教學,藉此一窺 Python 的能力,並提供一個學習的入門階。
  • 3. 今日內容: 初學 Python 型別 Types ,運算 Operators 語法 Statements 函數 Functions 模組 Modules 物件 Classes 例外處理 Exceptions 常用 Python Modules Python Web CGI howto
  • 4. Python 是什麼? 1990 年代初由 Guido 開發的程式語言 泛用性的動態物件導向程式語言 應用於系統管理 網路管理 網路傳輸程式 網頁程式開發 數值分析程式 圖形介面應用程式
  • 5. 誰在用 Python ? Google Youtube BitTorrent NASA OLPC Plurk
  • 6. Python 特色 ? 方便的 Python 快速的 Python 跨平台的 Python 高彈性的 Python
  • 7. Python 語言特性 ? Script 特性 語法強迫縮排 直譯器 動態語言特性 物件導向 跨平台 Python program is Python module Duck type 豐富的線上說明跟手冊
  • 8. 一分鐘學 python import os def do_func(): mylst=['hello','world',2,'python!'] for x in mylst: print x, a='ls -al' if a=='ls -al': do_func() os.system(a)
  • 9.  
  • 10. 30 分鐘學 python Interpreter Python String Slices List Slices advanced for loop while loop def function (): help(), dir(),type()
  • 11. 六小時學 python ? 你等一下就會知道了
  • 12. 日本 Ruby 會長高橋征義說 輕量之人 怠惰 勤勉之人 多數派 - 努力工作 勤勉之人用的語言 Cobol C/C++ java 程式設計師在 日本 有兩類 輕量之人用的語言 Ruby Perl Python 勤勉之人 寫很多程式碼 一個方法 1000 行 輕量之人 1000 方法一行
  • 13. 可讀性語言 VS 唯寫性語言 #!/bin/sh # t2h {$1} html-ize a text file and save as foo.htm NL=&quot; &quot; cat $1 \ | sed -e 's/ at / at /g' \ | sed -e 's/[[:cntrl:]]/ /g'\ | sed -e 's/^[[:space:]]*$//g' \ | sed -e '/^$/{'&quot;$NL&quot;'N'&quot;$NL&quot;'/^\n$/D'&quot;$NL&quot;'}' \ | sed -e 's/^$/<\/UL><P>/g' \ | sed -e '/<P>$/{'&quot;$NL&quot;'N'&quot;$NL&quot;'s/\n//'&quot;$NL&quot;'}'\ | sed -e 's/<P>[[:space:]]*&quot;/<P><UL>&quot;/' \ | sed -e 's/^[[:space:]]*-/<BR> -/g' \ | sed -e 's/http:\/\/[[:graph:]\.\/]*/<A HREF=&quot;&&quot;>[&]<\/A> /g'\ > foo.htm
  • 14. 可讀性語言 VS 唯寫性語言 echo -e &quot;192.168.1.243 1000 T\n 192.168.1.243 1001 T \n 192.168.1.243 1002 L&quot; | sed 's/\(100\)\(.\)/\1\20/' echo '&#228;&#184;&#173;&#230;&#150;&#135;' |perl -p -e 's/&#(\d+);/chr($1)/eg'
  • 15. 一分鐘學 python import os def do_func(): mylst=['hello','world',2,'python!'] for x in mylst: print x, a='ls -al' if a=='ls -al': do_func() os.system(a)
  • 17. 初學 Python 下載 & 安裝 & 移除 google -> python download http://www.python.org/download/ 直譯器的使用 hello world python Python 教學文件 http://tinyurl.com/jubwx Python 學習手冊 http://tinyurl.com/c9ga73
  • 18. 型別 Types ,運算 Operators 數字 Numbers python 計算機 >>> a = 5 >>> a + 1 >>> a + _ >>> a + _ >>> a / 3 ; a / 3.0 字串 String +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 >>> stra='abc ' >>> stra + stra >>> stra * 3
  • 19. 型別 Types ,運算 Operators 列 List a=['a','b','c','d','e'] b=[1,2,3,4,5,6,'abc'] c=[a,b,a,b] len(c) ; len(a) ; len(b) 字典 Dict tel = {'jack': 4098, 'sape': 4139} tel['guido'] = 4127 del tel['sape'] tel['irv'] = 4127 tel tel.keys() tel.keys()[1] tel.has_key('guido')
  • 20. 語法 Statements - if else if elif else >>> x = int(raw_input(&quot;Please enter a number: &quot;)) >>> if x < 0: ... x = 0 ... print 'Negative changed to zero' ... elif x == 0: ... print 'Zero' ... elif x == 1: ... print 'Single' ... else: ... print 'More' ...
  • 21. 語法 Statements - while while loop >>> a, b = 0, 1 >>> while b < 1000: ... print b, ... a, b = b, a+b ... 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
  • 22. 語法 Statements - for loop for loop >>> a = ['cat', 'window', 'defenestrate'] >>> for x in a: ... print x, len(x) ... cat 3 window 6 defenestrate 12
  • 23. 語法 Statements - for range for range() >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(0, 10, 3) [0, 3, 6, 9] >>> range(-10, -100, -30) [-10, -40, -70] >>> for i in range(1,10): ... print i, 1 2 3 4 5 6 7 8 9 >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print i, a[i], &quot;|&quot;, 0 Mary | 1 had | 2 a | 3 little | 4 lamb |
  • 24. 小試身手 99 乘法表 1x1=1 1x2=2 1x3=3..... 1x9=9 ..... 9x1=9 9x2=18 9x3=27 ... 9x9=81 提示 2 個 for 回圈 range(1,10) print &quot;xxx %d&quot;
  • 25. 函數 Functions def function(): >>> def fib(n): ... &quot;Print a Fibonacci series up to n&quot; ... a, b = 0, 1 ... while b < n: ... print b, ... a, b = b, a+b ... >>> fib(200) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
  • 26. 函數 Functions (n,m=0) def function(n,m=0): >>> def fib(n,m=0): ... &quot;Print a Fibonacci series up to n&quot; ... a, b = 0, 1 ... while b < n: ... if m < b: ... print b, ... a, b = b, a+b >>> fib(200) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 >>> fib(200,8) >>> fib(m=10,n=200)
  • 27. 函數 Functions default value def function(): default value def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while 1: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return 1 if ok in ('n', 'no', 'nop', 'nope'): return 0 retries = retries - 1 if retries < 0: raise IOError, 'refusenik user' print complaint >>> ask_ok('Do you really want to quit?') >>> ask_ok('OK to overwrite the file?', 2)
  • 28. 函數 Functions default value def function(): default value def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): while 1: ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return 1 if ok in ('n', 'no', 'nop', 'nope'): return 0 retries = retries - 1 if retries < 0: raise IOError, 'refusenik user' print complaint >>> ask_ok('Do you really want to quit?') >>> ask_ok('OK to overwrite the file?', 2)
  • 29. 函數 Functions return list def function(): return >>> def fib2(n): ... result = [] ... a, b = 0, 1 ... while b < n: ... result.append(b) ... a, b = b, a+b ... return result ... >>> f100 = fib2(100) # call it >>> f100 # write the result [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
  • 30. 函數 Functions return value def function(): return >>> def fib2(n,m): ... result = [] ... a, b = 0, 1 ... while b < n: ... result.append(b) ... a, b = b, a+b ... return result[-m:] ... >>> a , b = fib2(100,2) >>> print &quot;a=%d b=%d&quot; % (a,b) a=55 b=89
  • 31. 模組 Modules - Python modules Namespaces are one honking great idea -- let's do more of those! (Zen of Python) split your program into several files for easier maintenance . A module is just a python script with a .py suffix. Syntax: import modulename Your python script is already a module.
  • 32. 模組 Modules - fibo.py def fib(n): &quot;write Fibonacci series up to n. hi This fib help menu&quot; a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): &quot;&quot;&quot; return Fibonacci series up to n hi This fib2 help menu &quot;&quot;&quot; a, b = 0, 1 result = [] while b < n: result.append(b); a, b = b, a+b return result if __name__ == '__main__': fib(100) f100=fib2(100) print f100
  • 33. 模組 Modules >>> import fibo >>> fibo.fib(1000) >>> fibo.fib2(1000) >>> fib=fibo.fib >>> fib(500) >>> fib2=fibo2.fib >>> fib2(500) >>> from fibo import fib, fib2 >>> fib(500) >>> fib2(500)
  • 34. 模組 Modules dir() help() >>> import fibo, sys >>> dir (fibo) >>> dir (fibo.fib) >>> dir (fibo.fib2) >>> help (fibo) >>> help (fib) >>> help (fib2) >>> dir (sys) >>> help (sys)
  • 35. Python Modules HOWTO 寫個 modules 感受一下
  • 36. 物件 Classes class FClass: def setdata(self, value): self.data = value def display(self): print self.data x=FClass() y=FClass() x.setdata(&quot;hi all&quot;) y.setdata(7654321) x.display() y.display() x.data=&quot;rewrite data&quot; x.display()
  • 37. 物件 Classes class SClass(FClass): def display(self): print 'SClass value display %s' % self.data z=SClass() z.setdata(42) z.display() x.display()
  • 38. 物件 Classes class TClass(SClass): def __init__(self, value): self.data = value def __add__(self, other): return TClass(self.data + other) def __mul__(self, other): self.data = self.data * other a=TClass(&quot;abc &quot;) a.display() b = a + &quot;xyz&quot; b.display() a * 3 a.display()
  • 39. 例外處理 Exceptions except (TypeError,someError) : try: try_something() except: do_otherthing() else: do_closing() finally: try: try_something() finally: do_final()
  • 40. 例外處理 Exceptions #!/usr/bin/python while 1: try: x = int(raw_input(&quot;Please enter a number: &quot;)) break except ValueError: print &quot;Oops! That was no valid number. Try again...&quot; print &quot;You input number is %d&quot; % (x)
  • 41. 例外處理 Exceptions >>> try: ... raise KeyboardInterrupt ... finally: ... print 'Goodbye, world!' ... Goodbye, world! Traceback (innermost last): File &quot;<stdin>&quot;, line 2 KeyboardInterrupt
  • 42. 常用 Python Modules import os import re import string import time import sys import cgi import cgitb import urllib import telnetlib import ftplib
  • 43. Lots of Python Modules….. Standard Python Modules http://www.python.org/doc/current/modindex.html PyPI:the Python Package Index: third-party Python packages. http://www.python.org/pypi
  • 44. Python Web CGI howto CGI cgi-test.py #!/usr/bin/python import cgi, string, re, os, sys, time CGI_HTMLHEAD=&quot;Content-type: text/html\n\n&quot; print CGI_HTMLHEAD print &quot;<h3>&quot; print time.ctime() print &quot;</h3>&quot;
  • 45. Python Web CGI howto HTML setup.html DNS1 Server: <input type=&quot;text&quot; id=&quot;dns1&quot; name=&quot;dns1&quot;/> <input type=&quot;submit&quot; name=&quot;OK&quot; value=&quot; 確定 &quot; /> CGI setup.py import cgi, string, re, os, sys, time CGI_HTMLHEAD=&quot;Content-type: text/html\n\n&quot; print CGI_HTMLHEAD form = cgi.FieldStorage() if form.has_key('OK'): print &quot;<h1>&quot; print &quot;%s&quot; % (form['dns1'].value) print &quot;</h1>&quot;
  • 46. 其他線上文件 For beginer: http://wiki.python.org.tw/ThinkLikeComputerScientist http://wiki.python.org/moin/BeginnersGuide/NonProgrammers For experienced programmer: http://docs.python.org/tut/tut.html http://www.diveintopython.org/ http://wiki.python.org/moin/BeginnersGuide/Programmers Books for python: http://wiki.python.org/moin/PythonBooks
  • 48. Zen of Python python –c “import this” Simple is better than complex. (C++) Complex is better than complicated. (Java) Readability counts. (Perl) If the implementation is hard to explain, it's a bad idea. (Java framework like EJB) Explicit is better than implicit. (ruby on rails?) There should be one-- and preferably only one --obvious way to do it.
  • 49. 新手 : 你怎麼飛的 ??? 答 : import antigravity

Editor's Notes

  • #2: Python 入門
  • #3: 簡介
  • #4: Toc
  • #5: what is python
  • #6: who using python
  • #7: what is python more
  • #8: what is python more about 語言特性
  • #9: One Minute Python Tutorial
  • #10: python vs java
  • #11: 30 min Python Tutorial
  • #12: 6 hr Python Tutorial
  • #13: peopel
  • #14: read able vs write able [html|sed]
  • #15: read able vs write able [perl]
  • #16: One Minute Python Tutorial
  • #17: 行前叮嚀
  • #18: 初學 Python
  • #19: Type Operators
  • #20: Type Operators
  • #21: Statements if else
  • #22: Statements - while
  • #23: statements - for loop
  • #24: statements for range
  • #25: 小試身手
  • #26: Functions
  • #27: Functions (n,m=0)
  • #28: Functions default value
  • #29: Functions default vale modify
  • #30: Function return list
  • #31: Functions return value a b
  • #32: Python Modules
  • #33: Python Modules fibo.py
  • #34: Python modules using.py
  • #35: python modules dir() help()
  • #36: Python modules HOWTO
  • #37: Classes 0
  • #38: Classes 1
  • #39: Clasess 2
  • #40: 例外處理
  • #41: Exceptions [ex]
  • #42: Exceptions [ex finally]
  • #43: 常用 Python Modules
  • #44: Lots of Python Modules.....
  • #45: Python Web CGI howto
  • #46: Python Web CGI howto
  • #47: 線上文件
  • #48: kill egg
  • #49: Zen of Python
  • #50: import antigravity
  • #51: thx.