自由軟體工作坊 - Python 入門

download 自由軟體工作坊 - Python 入門

If you can't read please download the document

Transcript of 自由軟體工作坊 - Python 入門

- Python Python tutorial

Lloyd Huang [email protected]

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

pythonimport 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 pythonInterpreter Python String Slices List Slices advanced for loop while loop def function (): help(), dir(),type()

python

Ruby 1000 1000 - Cobol C/C++ java Ruby Perl Python

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"'/^\n$/D'"$NL"'}' \ | sed -e 's/^$//g' \ | sed -e '/$/{'"$NL"'N'"$NL"'s/\n//'"$NL"'}'\ | sed -e 's/[[:space:]]*"/

  • "/' \ | sed -e 's/^[[:space:]]*-/
    -/g' \ | sed -e 's/http:\/\/[[:graph:]\.\/]*/[&] /g'\ > foo.htm

    VS echo -e "192.168.1.243 1000 T\n 192.168.1.243 1001 T \n 192.168.1.243 1002 L" | sed 's/\(100\)\(.\)/\1\20/' echo '& #150;' |perl -p -e 's/(\d+);/ch r($1)/eg'

    pythonimport 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 ht ://t y r o /ju w t p in ul.c m b x

    Python http://tinyurl.com/c9ga73

    Types Operators Numbers python >>> >>> >>> >>> >>> a a a a a =5 +1 +_ +_ / 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

    Types Operators Lista ['a ','c ','e = ','b ','d '] b [1 ,3 ,5 ,'a c = ,2 ,4 ,6 b '] c [a ,a ] = ,b ,b le (c ; le (a ; le (b n) n) n)

    Dt ict l ={ c ': 4 9 , 's p ': 4 3 } e 'ja k 0 8 a e 1 9 t l['g id ']=4 2 e u o 17 d l t l['s p '] e e ae t l['ir ']=4 2 e v 17 tl e t l.k y () e es t l.k y ()[1 e es ] t l.h s k y u o e a _ e ('g id ')

    Statements - if elseif 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' ...

    Statements - whilewhile 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 loopfor loop>>> a = ['cat', 'window', 'defenestrate'] >>> for x in a: ... print x, len(x) ...

    cat 3 window 6 defenestrate 12

    Statements for range()>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    for range

    >>> 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, 123456789 >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] >>> for i in range(len(a)): ... print i, a[i], "|",

    99 1x1=1 1x2=2 1x3=3..... 1x9=9 ..... 9x1=9 9x2=18 9x3=27 ... 9x9=81 2 for range(1,10) print "xxx %d"

    Functionsdef 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

    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)

    Functionsdef ask_ok(prompt, please!'): retries=4,

    default value

    def function(): default valuecomplaint='Yes or no,

    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)

    Functionsdef ask_ok(prompt, please!'): retries=4,

    default value

    def function(): default valuecomplaint='Yes or no,

    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 "a=%d b=%d" % (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): "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

    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

    Classesclass FClass: def setdata(self, value): self.data = value def display(self): print self.data x=FClass() y=FClass() x.setdata("hi all") y.setdata(7654321) x.display() y.display() x.data="rewrite data" x.display()

    Classesclass SClass(FClass): def display(self):print 'SClass value display %s' % self.data

    z=SClass() z.setdata(42) z.display() x.display()

    Classesclass 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("abc ") a.display() b = a + "xyz" b.display() a*3 a.display()

    Exceptionsexcept(TypeError,someError) : try: try_something() except: do_otherthing() else: do_closing()

    finally:try: try_something() finally: do_final()

    Exceptions#!/usr/bin/pythonwhile 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)

    Exceptions>>> try: ... raise KeyboardInterrupt ... finally: ... print 'Goodbye, world!' ... Goodbye, world! Traceback (innermost last): File "", line 2 KeyboardInterrupt

    Python Modulesimport os imotr pr e imotsr g p r t in imott e p r im imots s pr y imotc i pr g imotc it pr g b imotullib pr r imott ln t p r e elib imotft lib pr p

    Lots of Python Modules..

    Standard Python Moduleshttp://www.python.org/doc/current/modindex.html

    PyPI:the Python Package Index:third-party Python packages. http://www.python.org/pypi

    Python Web CGI howtoCGI cgi-test.py#!/usr/bin/python import cgi, string, re, os, sys, time CGI_HTMLHEAD="Content-type: text/html\n\n" print CGI_HTMLHEAD print "" print time.ctime() print ""

    Python Web CGI howtoHTML setup.htmlDNS1 Server:

    CGI setup.pyimport cgi, string, re, os, sys, time CGI_HTMLHEAD="Content-type: text/html\n\n" print CGI_HTMLHEAD form = cgi.FieldStorage() if form.has_key('OK'): print "" print "%s" % (form['dns1'].value) print ""

    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 Pythonpython 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.

    : : imota t r v y p r niga it

    ???

    by Lloyd@ZZZzzz...