Python Ko-Lung Yuan Why Python? • • • • • • • • • Simple and elegant Good readability Object-oriented / dynamic(script) language High productivity Abundant resources(libraries…) Active community Wide range of uses Embeddable and Extendibility Interactive Learning / well document Python’s history • http://zh.wikipedia.org/wiki/Python Guido van Rossum Zen of Python • • • • • • • • • • • • • • • • • • • Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! Python之禪 • • • • • • • • • • • • 美麗優於醜陋,明講好過暗諭。 簡潔者為上,複雜者次之,繁澀者為下。 平舖善於層疊,勻散勝過稠密;以致輕鬆易讀。 特例難免但不可打破原則,務求純淨卻不可不切實際。 斷勿使錯誤靜靜流逝,除非有意如此。 在模擬兩可之間,拒絕猜測的誘惑。 總會有一種明確的寫法,最好也只有一種, 但或須細想方可得。 凡事雖應三思後行,但坐而言不如起而行。 難以解釋的實作方式,必定是壞方法。 容易解釋的實作方式,可能是好主意。 命名空間讚,吾人多實用。 蟒之道 • • • • • • • • • 妍優於寢 喻莫如敘 是故簡勝繁 繁勝亂 平舖勝汲營 綿密不如疏俊 唯平易而已 無例外於其例 不獨清於實際 毋默於誤 其惡非務 寧戚戚於尋徑 勿揣揣於模稜 道謀於一 可以得矣 力行者宜立行於當下 利行者長三思而後行 不可說之說不可說 可以道之道可以道 名域鳴於域 可取 How to Get Python • Official website: http://www.python.org/ Install Python • Python Interpreter and Libraries • Linux: sudo apt-get install python3.1-dev IDLE • A basic but useful editor for Python • • • • Text-Indent Keyword-Highlight Interactive interface Easy to test code First, We should know… • No semicolon ( • No brace ( ;) X { }) : • Using colon ( ) • Using text-Indent X O O Comment • Single-line comment ( #) # This is an example of single-line comment • Multi-line comment ( “”” “”” ) “””This is an example of multi-line comment You can write the comment in several lines””” Variable • Build variable ( Var = … ) Var = 70 Var = 6.78 Var = “alcom lab” • No declaration but definition and type • Naming Rule • No need to worry about where the variables and their sizes, all of the details are hided! Input and Output • Output ( print() ) print(100) print(“a=”,a) • Input ( raw_input( [hint] ) ) raw_input(“name:”) String • Using quote ( ‘ ’, “ ”, “”” ””” ) s1=‘apple’ s2=“banana” s3=“””I love you””” print(s1,s2,s3) • Strings are unchanged object • Using escape characters(e.g. /n) String Operation • Concatenate( +) *n ) Length( len() ) Exist( in ) “alcom”+”lab” • Repeat( “go”*3 • len(“three”) • • Split( ‘a’ in ‘apple’ .split(“string”) ) “abc cde”.split(“ ”) Mathematic Type • Integer - no limit 123123123112432532643877698709760909 • Float – Not exact, support science notation 123.456 1.2e-3 • Complex number 1+2j 1.23+34.7+5j Mathematic Operation • Basic operation + - * / % • Floating Point –base on simple one 10/3 50*0.5 10+3j-3j • Special operation ** // 16**0.5 10.0//3.0 All things in python are objects! List • An ordered data structure (Like array) • Mutable Sequence • [object 1, object 2, …] listex = [1, 2.34, ”alcom”, 7+8j] • Support Nested List nestlist = [ [1,2,3] , [4.2, “john”], Var] • Access method listex[-1] nestlist[0][2] List Operation • • • • • • • • • • Length Append Extend Count Index Insert Pop Remove Reverse Sort len(nestlist) listex.append(20) listex.extend([2,3,4]) [1,1,2,3].count(1) [1,1,2,3].index(1) [1,1,2,3].insert(1,1) [1,1,2,3].pop() [1,1,2,3].remove() [1,2,3,4].reverse() [1,2,3,4].sort() Dictionary • Dictionary is a mapping object Key value D = { key1:value1, key2:value2, …} D[key] = value D[key] • Dictionary is unordered • Set is another unordered data structure Slice • S[ i ] • S[ i : j ] • S[ i : j : k ] • Some examples If else if condition: … elif condition: … else: … PS : Text-Indent!! Logical Operation • • • • • • • == != < > <= >= Or And Not Boolean value: True False For Loop For Var in container: …code… …code… For Var in range(x): …code… …code… Container • • • • • • Container are the iterative objects List: elements of list Dictionary: keys of dictionary Tuple: elements of tuple File: lines of file range(x): build a list [0, 1, 2, … ,x-1] In and List Comprehension •In is an useful keyword 1. in relation 2. for iteration if a in “abc” for a in list: • List Comprehension List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] List2 = [item*10 for item in List] While Loop While condition: …code… While True: …code… Nested Structure • • • • We can use nested structure in python For loop While loop If elif else Build-in Function len() • Sort: sorted() • Length: V.s. object.sort() Function Factory • Change object type! • int( ) • str( ) • float( ) Module / Import / Namespace • A .py file is a module whose name is same as the file name • Use module by import import sys • Every module has a namespace of its own – Original-> (main) – Import one-> It’s name User Function • def funciton_name(parameters[=default value]): …function description… • Call function namespace.function_name(parameters) namespace.function_name(parameters, appointed parameter1=value, appointed parameter2=value, …) Other important issues • • • • • User Object File IO (simple demo) Exception Handling Pypi pickle Strong Python • • • • • APPs Website(server program) Linux Shell Script / Linux Managing Latex Combine with C/C++ Python with Linux (1/2) • • • • • • • • #!/usr/bin/python # -*- coding: UTF-8 -*Import os and shutil os.unlink('data.new.txt') os.rename('data.txt', 'data.alter.txt') shutil.copy('data.txt', 'data.new.txt') shutil.move('data.alter.txt', 'data.txt') chmod a+x python-script-file Python with Linux (2/2) • Run outer program os.system(“program”) • Pipeline and get the return value import popen2 stdout, stdin = popen2.popen2(“ls”) ostr = stdout.read() print(ostr) Python with C/C++ • http://docs.python.org/extending/extending. html Python with Latex • http://www.texample.net/weblog/2008/oct/2 4/embedding-python-latex/ Useful Books • • • • • Head First Python Dive into Python Programming in Python3 Python Essential Reference Learning Python Useful Websites • http://ez2learn.com/index.php/pythontutorials • http://wiki.python.org.tw/ • http://caterpillar.onlyfun.net/Gossip/Python/i ndex.html • http://pypi.python.org/pypi