13. 可讀性語言 VS 唯寫性語言 #!/bin/sh # t2h {$1} html-ize a text file and save as foo.htm NL=" " cat $1 | sed -e 's/ at / at /g' | sed -e 's/[[:cntrl:]]/ /g'| sed -e 's/^[[:space:]]*$//g' | sed -e '/^$/{'"$NL"'N'"$NL"'/^$/D'"$NL"'}' | sed -e 's/^$/<UL><P>/g' | sed -e '/<P>$/{'"$NL"'N'"$NL"'s///'"$NL"'}'| sed -e 's/<P>[[:space:]]*"/<P><UL>"/' | sed -e 's/^[[:space:]]*-/<BR> -/g' | sed -e 's/http:[[:graph:]]*/<A HREF="&">[&]<A> /g'> foo.htm
14. 可讀性語言 VS 唯寫性語言 echo -e "192.168.1.243 1000 T 192.168.1.243 1001 T 192.168.1.243 1002 L" | sed 's/100./0/' echo '中文' |perl -p -e 's/&#(+);/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)
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("Please enter a number: ")) >>> 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], "|", 0 Mary | 1 had | 2 a | 3 little | 4 lamb |
25. 函數 Functions def function(): >>> def fib(n): ... "Print a Fibonacci series up to n" ... 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): ... "Print a Fibonacci series up to n" ... 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 "a=%d b=%d" % (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): "write Fibonacci series up to n. hi This fib help menu" a, b = 0, 1 while b < n: print b, a, b = b, a+b def fib2(n): """ return Fibonacci series up to n hi This fib2 help menu """ 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
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)
40. 例外處理 Exceptions #!/usr/bin/python while 1: try: x = int(raw_input("Please enter a number: ")) break except ValueError: print "Oops! That was no valid number. Try again..." print "You input number is %d" % (x)
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.