Python

Document Sample
Python
Description

ไพธอน เป็นภาษาโปรแกรมในลักษณะภาษาอินเตอร์พรีเตอร์โปรแกรมมิ่ง การจัดชนิดของตัวแปรผันตามข้อมูลที่บรรจุอยู่

ไพธอนนั้นเป็น Open Source เป็นภาษาที่ใช้งานได้หลากหลาย โดยจะมองอะไรที่มากกว่าการโค๊ดดิ้ง แต่จะมองเป็น OOP

Python programming language



2



46320388 46320511 46320610 46320693 46320818 46320925 46321097 46321139 46321150



3



4



, , , ,



5



6



1 1.1 . . . . . . . . . . 1.1.1 . . . . . . . . . . 1.1.2 . . . . . . . . . . 1.1.3 . . . . . . . . . . . . . . . . . . . . Language Evaluation Criteria . . . . . . . . . . . . . . . . . . . . Category Application Domains . . . . . 1.5.1 Web Internet Development . . . 1.5.2 Database Access . . . . . . . . . . . 1.5.3 Desktop GUI . . . . . . . . . . . . . 1.5.4 Scientific Numeric computation 1.5.5 Education . . . . . . . . . . . . . . . 1.5.6 Network programming . . . . . . . . 1.5.7 Software builder Testing . . . . 1.5.8 Game 3D Graphics Rendering . . . . . . . . . . . . . . . . . . . . (Printing) (Reserved word Keywords) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (Reserved words, Keywords) . . . . . . . . . . . . . . . . . . . (Arithmetic Mathematics) (normal arithmetic operators) . . . . . . . . . . . . . (Built-in Math Functions) . . . . . . . . . (absolute value) . . . . . . . . . . . . . . . . . (smallest or largest values) (specified number of digits) . . . . . (adds numbers in a sequence.) . . . (range of numbers.) . . . . . . . . . . . . . . 7 . . . . . . . Python 1.0 Python 2.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .



1.2 1.3 1.4 1.5



1.6 1.7 2 3 3.1 3.2 4 4.1 4.2



13 13 13 14 14 15 15 15 16 16 16 17 17 17 17 17 17 17 18 21 23 23 23 25 25 26 26 26 27 27 27



4.2.1 4.2.2 4.2.3 4.2.4 4.2.5



. . . . . . .



. . . . . . .



. . . . . . .



. . . . . . .



. . . . . . .



. . . . . . .



8 5 5.1 5.1.1 5.1.2 5.1.3 5.2 5.2.1 5.2.2 5.2.3 5.2.4 5.2.5 5.3 5.3.1 6 7 7.1 7.2 7.3 8 scope) 8.1 8.2 9 9.1 9.1.1 9.1.2 9.2 9.2.1 9.2.2 9.2.3 9.2.4 9.3 9.3.1 9.3.2 10 10.1 10.2 11 (Data type) (Numbers) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (Integers) . . . . . . . . . . . . . . . . . . . . . . . . . . (Floating-point numbers) . . . . . . . . . . . . . . . . (Complex Numbers) . . . . . . . . . . . . . . . . . (Collection Data Types) . . . . . . . . . . (List) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (Dictionary Groupings of Data Indexed by Name) (Tuples) (Sequences) . . . . . . . . . . . . . . (Sets) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (String Array of Characters) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (Comparisons) (Boolean AND ( ) . . . . . . . . OR ( ) . . . . . . . . NOT ( ) . . . . . . . . . Expressions) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . (Life time Variable 49 49 49 51 51 51 53 53 53 53 54 55 55 55 56 59 60 62 63 29 29 29 30 31 32 32 33 34 34 35 39 42 45 47 47 47 48



. . . . . . . . . . . .



. . . . . . . . . . . .



. . . . . . . . . . . .



. . . . . . . . . . . .



. . . . . . . . . . . .



(Statement block)



(Statement block) . . . . . . . . . . . . . . . . . . . . . . . . . . (Life time Variable scope) . . . . . . . . . . . . . . . . . . (Control flow, Flow of Control (Decisions, Choice Selection) . . . . . . . . if Statements . . . . . . . . . . . . . . . . . . . . . . switch Statements . . . . . . . . . . . . . . . . . . . (Loop) . . . . . . . . . . . . . . . . . . . . . . . while Statements . . . . . . . . . . . . . . . . . . . . for Statements . . . . . . . . . . . . . . . . . . . . . pass, break, continue else Clauses Statements . . do-while Statements . . . . . . . . . . . . . . . . . . (Error Checking) . . . . . assert Statements . . . . . . . . . . . . . . . . . . . . try-except raise Statements (Exception handling) (Defined Function) , Global ( ) Local ( Alternatively) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .



. . . . . . . . . . .



. . . . . . . . . . .



. . . . . . . . . . .



. . . . . . . . . . . . . ) . . . . . . . . . . . . . . . . . .



(Input Data from Keyboard)



9 Python Python, wxPython Stani’s Python Editor Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . wxPython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Stani’s Python Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . SPE Sidebar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 69 69 72 75 79 80 81 81 85 85 86 87



.1 .2 .3



.0.1 .0.2 .0.3



, Debug .1 .2 Debug SPE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .



10



1.1 .1 .2 .3 .4 .5 .6 .7 .8 .9 .10 .11 .12 .13 .14 .15 .16 .17 .18 .19 .20 .21 .22 .1 .2



Guido van Rossum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Python 2.4 1: 2: 3: 4: 5: 6: Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "Install for all users" . . . . . . . . . . . . . . . . . . . . . . . . C:\Python24\ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . wxPython runtime for Python 2.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1: 2: 3: 4: 5: 6 : Finish component . . . . . . . . . . . . . . . . . . . . . . . . . . Next . . . . . . . . . . . . . . . . . . . . . . . . Next . . . . . . . . . . . checkbox . . . . . . . . . . . . . . . Yes . . . . . . . . . . . . . . . . . . . . . .



14 69 70 70 70 71 71 71 72 72 73 73 73 73 74 74 75 75 76 76 76 77 77 79 80 81 82 82 82



Stani´ Python Editor Version 0.8.2.a s Windows SourceForge (mirror) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1: 2: 3: 4: 5: Stani’s Python Editor Next . . . . . . . . . . . . . . . . . . . . . . . . . . Next . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SPE . . . . . . . . . . .



Stani’s Python Editor (SPE) . . . . . . . . . . . . . . . . . . . . .



.3 Shell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 Local object browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11



12 .1 .2 .3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Error Debug . . . . . . . . . . . . . . . . . . . . . . . . 85 85 86



1



(Python) gramming language)



(Interpreted pro-



Guido van Rossum 1990 (Fully dynamically typed) (Automatic memory management) ABC, Modula-3, Icon, ANSI C, Perl, Lisp, Smalltalk Tcl Ruby Boo Open source Foundation ( . * 25 2549) 2.4.3 ( 29 2.5 ( 2549) Python Software http://www.python.org/ 19 2549)



1.1

1.1.1 Python 1.0



1990 Guido van Rossum CWI (National Research Institute for Mathematics and Computer Science) ABC Modula-3, Icon, C, Perl, Lisp, Smalltalk Tcl Duido van Rossim Benevolent Dictator for Life (BDFL) BDFL Linus Torvalds Linux kernel, Larry Wall Perl programming language 1.2 1995 ration for National Research Initiatives (CNRI) 1.6 1.6 Guido van Rossum CNRI Guido , CNRI CNRI Free Software Foundation (FSF) Corpo-



General Public License (GPL)



13



14



1.1: Guido van Rossum GPL-compatible GPL Guido van Russom Software" 1.6.1 GPL-compatible license ( ) FSF "Advancement of Free 1.6



1.1.2



Python 2.0

2000 Guido Python Core Development team BeOpen.com BeOpen PythonLabs team 2.0 BeOpen.com 2.0 BeOpen.com Guido PythonLabs Digital Creations 2.1 1.6.1 2.0 Python Software Foundation License Python Software Foundation (PSF) Apache Software Foundation 2.1 alpha



1.1.3

3.0 Python 3000 (Py3K) by removing old ways of doing things" ( ) (PEP) • 2.x "reduce feature duplication 3.0 Python Enhancement Proposal



1.2 • • relative imports • unicode/str separate mutable bytes type



15



classic class, classic division, string exceptions



implicit



1.2

(Multi-paradigm language) coding (Paradigm) Object-oriented programming, Structured programming, Functional programming Aspect-oriented programming (dynamically type-checked) Garbage collection



1.3



Language Evaluation Criteria

(Readability) (Writability) (Reliability) (Cost)



Open source



1.4

1.



Text File 2. Python Software Foundation License (PSFL) Python Software Foundation (PSF) General Public License (GPL) Free Software Foundation (FSF) Unix Platform, Windows Platform, OS/2, Amiga, Mac OS X Framework, Java virtual machine Nokia Series 60 Linux .NET



3.



16 4. Modula-3, Icon, ANSI C, Perl, Lisp, Smalltalk 5. 6. Java libraries Java Virtual Machine .NET Platform Tcl CORBA objects ABC,



COM, .NET Jython



7.



IronPython .Net Framework



Microsoft Python for .NET



8.



Internet Communications Engine (ICE)



9. extension modules SWIG 10. Server Boost.Python Server side Script Client C C++



11. CMS



Content Management Systems (CMS) Plone http://www.plone.org/



1.5



Category



Application Domains

Category (Multi-paradigm Object-oriented programming, Imperative, Functional programming



language) Logic programming



1.5.1



Web

Django



Internet Development

Web Development Zope, mega frameTurboGears Content Management Systems Plone Common Gateway Interface (CGI)



works CPS



1.5.2



Database Access

ODBC MySQL, Oracle, MS



Interfaces Database Connection Interface SQL Server, PostgreSQL, SybODBC



1.6



17



1.5.3



Desktop GUI



Tk GUI development library libraries Microsoft Foundation Classes (MFC, win32 extensions), wxWidgets, GTK, Qt, Delphi Graphic user interface



1.5.4

s



Scientific



Numeric computation

, Bioinformatics Physic-



1.5.5



Education

programming Python Software Foundation pyBiblio Software Carpentry Course



1.5.6



Network programming

Web Internet Development network programming sockets Twisted Framework Asyncronous network programming



mudules



1.5.7



Software builder



Testing



• Scons • Buildbot • Roundup



build Apache Gump Trac bug tracking Automated continuous compilation project management Testing



1.5.8



Game

Game libraries



3D Graphics Rendering

PyGame PyKyra Framework 3D Graphics Rendering



1.6

• BitTorrent age Tracker BitTorrent, Pack-



18 • Blender • Chandler , Microsoft • Civilization IV , • Mailman • Kombilo • MoinMoin • OpenRPG • Plone • Trac wiki Wiki Role Playing Games Content Management System MoinMoin Subversion Source version control Framework Cherrypy, SQLObject, MochiKit Internet E-Mail mailing lists boost.python , open source 3D modeling (Personal Information Manager, PIM) Outlook



• Turbogears KID templates • ViewVC • Zope • Battlefield 2 Web-based



CVS



SVN repositories



web-application platform First Person Shooter Configuration scripts Tsunami



• Indian Ocean Tsunami Detector • EVE Online Multi Massive Online Role Playing Game MMORPG.com



• SPE - Stani’s Python Editor Free open-source Python IDE for Windows, Linux & Mac with wxGlade (GUI designer), PyChecker (Code Doctor) Blender (3D) •



1.7

Industrial Light & Magic " Wars: Episode II crowd rendering batch processing compositing video " Tommy Burnette, Senior Technical Director, Industrial Light & Magic " ILM Star



1.7



19 "Philip Peterson, Principal Engineer, Research & Development, Industrial Light & Magic



Google "



Google



Google Google " Peter Norvig, Di-



rector of Search Quality, Google, Inc. NASA "NASA CAD/CAE/PDM libraries " STEP Testbed Model, Integration code Integration Transformation



Steve Waterbury, Software Group Leader, NASA



20



2 (Printing)

print String * Python C/C++, Java, ’String’ "String"



; (Semi-colon Symbol)



>>> print "Hello, World!"



Hello, World!



>>> >>> >>> >>>



print print print print



"Jack and Jill went up a hill" "to fetch a pail of water;" "Jack fell down, and broke his crown," "and Jill came tumbling after."



Jack and Jill went up a hill to fetch a pail of water; Jack fell down, and broke his crown, and Jill came tumbling after. * (Repetition Symbol)



>>> print "Hello, World!"*5



Hello, World!Hello, World!Hello, World!Hello, World!Hello, World! 21



22 * "#" Execute Program Comment Comment



(Printing)



>>> print "Foo" # Test Comment >>> print "Bar"



Foo Bar



3 (Reserved word Keywords)

3.1

1. 2. 3. 4. 5. (Reserved words, Keywords) underscore ( )



3.2



(Reserved words, Keywords)



and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while, yield, as ( 2.5) with ( 2.5) * 2.4.3 2.5 (Python Reference Manual Release 2.4.3, documentation updated on 29 March 2006 and Python Reference Manual Release 2.5, documentation updated on 19 September 2006)



23



24



(Reserved word



Keywords)



4 (Arithmetic Mathematics)

4.1 (normal arithmetic operators)

(normal arithmetic operators) • ** ( • *( • /( • %( • +( • -( , Exponentiation) , multiplication) , division) , remainder , addition) , subtraction) modulo)



1. 2. 3. 4.



(parentheses "()") (exponents "**" ) (multiplication "*" ), (addition "+") (division "/" ) (subtraction "-") (remainder/modulo "%" )



>>> i = 10 >>> f = 6.54 >>> print i + f 16.54 25



26



(Arithmetic Mathematics)



f



i float



10



f 16.54



6.54



i



integer



>>> >>> >>> >>> 8



i = 10 i = i + 6 i = i / 2 print i



>>> >>> >>> >>> 8



i = 10 i += 6 i /= 2 print i



C



4.2

4.2.1

Function



(Built-in Math Functions)

(absolute value)

abs(var) function var



>>> print abs(-6.5) 6.5



4.2.2

list, set



(smallest or largest values)

min(var) var max(var) list, set var , ,



>>> print min(6, 7, 2, 8, 5) 2 >>> print max(6, 7, 2, 8, 5)



4.2



(Built-in Math Functions)



27



8 >>> print min([0, 43.5, 19, 5, -6]) 0 >>> print max([0, 43.5, 19, 5, -6]) 43.5



4.2.3

round(var, digits)



(specified number of digits)



>>> print round(1234.56789, 2) 1234.57 >>> print round(1234.56789, -2) 1200.0



4.2.4



(adds numbers in a sequence.)

sum(sequence) sequence of numbers sum (1,2,3,4,5) 1



-5



>>> print sum((1, 2, 3, 4, 5)) 15



4.2.5



(range of numbers.)

range(start, end [,step]) 1 - 500



>>> print range(1, 6) [1, 2, 3, 4, 5]



>>> print sum(range(1, 6)) 15 1 - 6 m 2 ( n -1) m n m 1, 2, 3, 4, 5 n



>>> print range(1, 6, 2) [1, 3, 5]



28



(Arithmetic Mathematics)



5 (Data type)

Interpreter Programming Data type Data type Data type



(Data type)



5.1

5.1.1



(Numbers)

(Integers)

(Plain Integer)



Plain Integers +2147483647



int signed integer



32 bits



-2147483648



>>> x = 42 >>> type(x)



* function type(var) function casting data numbers 29 function int var interger



30 >>> x = int("17") >>> y = int(4.8) >>> print x, y, x - y



(Data type)



17 4 13 * function int(var) integer function var



(Long integer) Long integers - 2147483647 long signed integer + 2147483647 Long Integer



Integer L 234187626348292917L 7L



>>> googol = 10 ** 100 >>> print googol >>> type(googol) (Operator ** )



10000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000 googol (Boolean) Boolean bool long



• True • False -



1 0



5.1.2

Floating-point double



(Floating-point numbers)

float 64 bit double precision float float 7.8 x 10-28



1.23



5.1



(Numbers)



31



>>> debt = 7784834892156.63 >>> print debt >>> type(debt)



7.78483489216e+012 7.78483489216 x 10

12



function float >>> x = float(17) >>> y = float("4") >>> print x, y, x - y



17.0 4.0 13.0 * function float(var) floating-point function var



5.1.3

j j2 + 1 = 0



(Complex Numbers)

complex (imaginary number) z x y z x + iy x y



>>> imaginary_number = 16j >>> complex_number = 6 + 4j >>> print complex_number (6+4j) >>> print type(complex_number) j plex(real, [imag]) * function complex(real, imag) complex function real function com-



imag



32 >>>complex_number = complex(6, 4) >>>type(complex_number) >>>print(complex_number) (6+4j)



(Data type)



5.2

5.2.1 (List)



(Collection Data Types)



(Array) import module array list



(List)



square brackets "["



"]"



>>> i = [1, 2, 3, 4, ’Foo’, 5, ’Bar’] >>> print i >>> type(i)



[1, 2, 3, 4, ’Foo’, 5, ’Bar’] (index key) >>> print i[6]



Bar 0



0, 1, 2, 3, 4 , .... , n - 1 n list : (Colon Symbol)



>>> x = [1, 2, 3, 4, ’Foo’, 5, ’Bar’] >>> print x[3:5]



5.2



(Collection Data Types)



33



[4, ’Foo’]



>>> y = [10, 3, 5, 25, 7, 9] >>> z = [x for x in y if x >= 9] >>> print z



[10, 25, 9] 9



5.2.2

dict



(Dictionary

(Dictionary



Groupings of Data Indexed by Name)

value ( ( ) tuple keys:value



keys



Groupings of Data Indexed by Name) keys (associated key) (index key) ) list keys value keys



>>> >>> >>> >>>



i = {’first’:’alpha’,’last’:’omega’} print i print i[’first’] type(i)



{’last’: ’omega’, ’first’: ’alpha’} ’alpha’ first >>> print i[’first’] ’alpha’ >>> >>> >>> >>> >>> menus_specials = {} menus_specials[“breakfast”] = “canadian ham” menus_specials[“lunch”] = “tuna surprise” menus_specials[“dinner”] = “Cheeseburger Deluxe” print menus_specials[’breakfast’]



canadian ham



34



(Data type)



5.2.3

(



(Tuples)

, Tuples)



(Sequences)

tuple ( () )



>>> t = 12345, 54321, ’hello!’ >>> type(t) >>> t[0] 12345 >>> t (12345, 54321, ’hello!’) >>> # Tuples may be nested: ... u = t, (1, 2, 3, 4, 5) >>> u ((12345, 54321, ’hello!’), (1, 2, 3, 4, 5))



"," >>> empty = () >>> singleton = ’hello’, >>> len(empty) 0 >>> len(singleton) 1 >>> singleton (’hello’,) tuple



# >> x, y, z = t * 3 t



function



,



3



5.2.4



(Sets)

( )



5.2



(Collection Data Types) set List * function set(var) set var function



35 function set



>>> basket = [’apple’, ’orange’, ’apple’, ’pear’, ’orange’, ’banana’] >>> fruit = set(basket) # create a set without duplicates >>> type(fruit) >>> fruit set([’orange’, ’pear’, ’apple’, ’banana’]) >>> ’orange’ in fruit # fast membership testing True >>> ’crabgrass’ in fruit False >>> # Demonstrate set operations on unique letters from two words ... >>> a = set(’abracadabra’) >>> b = set(’alacazam’) >>> a # unique letters in a set([’a’, ’r’, ’b’, ’c’, ’d’]) >>> a - b # letters in a but not in b set([’r’, ’d’, ’b’]) >>> a | b # letters in either a or b set([’a’, ’c’, ’r’, ’d’, ’b’, ’m’, ’z’, ’l’]) >>> a & b # letters in both a and b set([’a’, ’c’]) >>> a ^ b # letters in a or b but not both set([’r’, ’d’, ’b’, ’m’, ’z’, ’l’])



5.2.5

* >>> i = [1,2,3,4] >>> print i.pop() 4 >>> j = {’first’:’alpha’,’last’:’omega’} >>> print j.pop(’first’) alpha Java



36 pop - [ / ]



(Data type)



Object.pop([key]) pop pop >>> i = [1,2,3,4] >>> print i.pop() 4 >>> j = {’first’:’alpha’,’last’:’omega’} >>> print j.pop(’first’) alpha append - [ ] pop



(index key) (associated key)



Object.append([object])



>>> i = [1,2,3,4] >>> print i.pop() 4 >>> i.append(5) >>> print i [1,2,3,5] insert - [ ] Object.insert(index, object)



>>> [1, >>> >>> [1, >>> >>> [1,



print i 3] i.insert(4, 5) print i 3, 5] i.insert(2, 6) print i 3, 6, 5] count - [ ] Object.count([object])



>>> i = [1,2,3,4] >>> print i.count(5)



5.2 0 >>> print i.count(4) 1 index - [ ]



(Collection Data Types)



37



Object.index(value, [ start , stop ]) (index key) >>> i = [1,2,3,4] >>> print i.index(4) 3 >>> print i.index(1) 0 extend - [ ]



Object.extend(list|dict)



>>> >>> >>> >>> [1,



j = {’last’: ’omega’} i = [1,2,3,4] i.extend(j) print i 2, 3, 4, ’last’] remove - [ ]



Object.remove(value)



>>> [1, >>> >>> [3,



print i 2, 3, 4, ’last’] i.remove(1) print i 6, 5, ’last’] sort - [ ] Object.sort() (sort)



>>> >>> >>> [1,



a = [5, 2, 3, 1, 4] a.sort() print a 2, 3, 4, 5]



38 >>> i = [’a’,’r’,’b’,’i’,’z’] >>> print i [’a’, ’r’, ’b’, ’i’, ’z’] >>> i.sort() >>> print i [’a’, ’b’, ’i’, ’r’, ’z’] reverse - [ ] (sort)



(Data type)



Object.reverse() >>> >>> >>> [1, >>> >>> [5, a = [5, 2, 3, 1, 4] a.sort() print a 2, 3, 4, 5] i.reverse() print i 4, 3, 2, 1] clear - [ ] Object.clear() >>> j = {’first’:’a’, ’second’:’b’} >>> print j {’second’: ’b’, ’first’: ’a’} >>> j.clear() >>> print j {} get - [ ] Object.get(key) >>> j = {’first’:’a’, ’second’:’b’} >>> print j {’second’: ’b’, ’first’: ’a’} >>> j.get(’first’) ’a’ has key - [ ]



Object.has key(key)



(associated key)



5.3



(String



Array of Characters)



39



>>> j = {’first’:’a’, ’second’:’b’} >>> print j {’second’: ’b’, ’first’: ’a’} >>> j.has_key(’first’) True >>> j.has_key(’last’) False items - [ ] Object.items(key)



>>> j = {’first’:’a’, ’second’:’b’} >>> print j {’second’: ’b’, ’first’: ’a’} >>>>>> j.items() [(’second’, ’b’), (’first’, ’a’)] keys - [ ] Object.keys()



>>> j = {’first’:’a’, ’second’:’b’} >>> print j {’second’: ’b’, ’first’: ’a’} >>>>>> j.keys() [’second’, ’first’] values - [ ]



Object.values() >>> j = {’first’:’a’, ’second’:’b’} >>> print j {’second’: ’b’, ’first’: ’a’} >>>>>>>>> j.values() [’b’, ’a’]



5.3

(Strings)



(String



Array of Characters)

1



(Array of Characters)



40 single quotation (’.....’) double quotation (" .... ") , 8-bit strings



(Data type)



Unicode objects



>>> print "Hello, World!"



Hello, World! function print , (Concatenation Symbol)



>>> >>> >>> >>> >>>



i = 5 print print print print



"14 / 3 = ",14 / 3 "14 % 3 = ",14 % 3 "14.0 / 3.0 =",14.0 / 3.0 "hello", "hello", i



14 / 3 = 4 14 % 3 = 2 14.0 / 3.0 = 4.66666666667 hello hello 5 Concatenation Symbol + (String Concatenation Symbol) print



>>> print "Jack and Jill went up a hill" + "to fetch a pail of water;" + "Jack fell down, and broke his crown," + "and Jill came tumbling after."



Jack and Jill went up a hill to fetch a pail of water; Jack fell down, and broke his crown, and Jill came tumbling after. double quotation



5.3 \newline \\ \’ \" \a \b \f \n \r \t \v



(String



Array of Characters) (Ignored) Backslash ( \) Single quote (’) Double quote (") Bell (BEL) Backspace (BS) Formfeed (FF) Linefeed (LF) Carriage Return (CR) Horizontal Tab (TAB) Vertical Tab (VT)



41



ASCII ASCII ASCII ASCII ASCII ASCII ASCII



String formatting operator "%"



>>> state = ’California’ >>> ’It never rains in sunny %s.’ %state



’It never rains in sunny California.’ %s s



d i o u x X e E f F g G c r s



Signed integer decimal Signed integer decimal Unsigned octal Unsigned decimal Unsigned hexidecimal (lowercase) Unsigned hexidecimal (uppercase) Floating point exponential format (lowercase) Floating point exponential format (uppercase) Floating point decimal format Floating point decimal format Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise Single character (accepts integer or single character string) String (converts any python object using repr()) String (converts any python object using str())



42



(Data type)



d = 4.5000 print ’It never print ’It never print ’It never print ’It never print ’It never print ’It never print ’It never print ’It never print ’It never print ’It never print ’It never print ’It never print ’It never print ’It never print ’It never



rains rains rains rains rains rains rains rains rains rains rains rains rains rains rains



in in in in in in in in in in in in in in in



sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny



%d.’ %i.’ %o.’ %u.’ %x.’ %X.’ %e.’ %E.’ %f.’ %F.’ %g.’ %G.’ %c.’ %r.’ %s.’



%d %d %d %d %d %d %d %d %d %d %d %d %int(d) %d %d



It It It It It It It It It It It It It It It



never never never never never never never never never never never never never never never



rains rains rains rains rains rains rains rains rains rains rains rains rains rains rains



in in in in in in in in in in in in in in in



sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny sunny



4. 4. 4. 4. 4. 4. 4.500000e+000. 4.500000E+000. 4.500000. 4.500000. 4.5. 4.5. L. 4.5. 4.5.



5.3.1

find Object.find((sub[, start[, end]]) (index key)



-1



5.3



(String



Array of Characters)



43



>>> s = "windows" >>> s.find(’dow’) 3 upper Object.upper() >>> s = "windows" >>> s.upper() WINDOWS lower Object.lower() >>> s = "WINDOWS" >>> s.lower() windows replace Object.replace(old, new) ( ) ( )



>>> s = ’The happy cat ran home.’ >>> s.replace(’cat’, ’dog’) ’The happy dog ran home.’



44



(Data type)



6 (Comparisons)



"in"



"is" "==" Boolean value



"is"



0



True False



False 1 True



Operator >= == != in is



>>> 1 True >>> 2 True >>> 2 True >>> 3 True >>> 0



0 >= 3 == 0



True >>> 0 True >>> x >>> 1 True >>> 1 True 45



!= 1 = [1,2,3,4] in x is 1



46



(Comparisons)



7 (Boolean Expressions)



(Condition) 1 AND, OR NOT



7.1



AND (

and



)

false false



false expression true and true true and false false and true false and false



True False False False



7.2

true



OR (

or



)

true true



expression true or true true or false false or true false or false



True True True False 47



48



(Boolean Expressions)



7.3



NOT ( )

not



expression not true not false



False True



>>> i = 1 >>> j = 2 >>> k = 3 >>> l = 1 >>> i == k and j == i False >>> i == k or l == i True >>> not i == k and l == i True



8 (Statement block) (Life time Variable scope)

8.1 (Statement block)

C ..... (indentation) >>> >>> >>> >>> >>> >>> x = 1 if x == 1: print "True" else: print "False" print "xxx" block True xxx if if : (colon) Python



8.2



(Life time



Variable scope)

x 5 x 6 2 x



hello 1 hello x global scope 49 print x 1 x 6 6 5 global 6 6



50 1 >>> >>> >>> >>> >>> >>> x = 5 def hello(): x = 6 print x hello() print x



(Statement block) 2 >>> >>> >>> >>> >>> >>> >>>



(Life time



Variable scope)



x = 5 def hello(): global x x = 6 print x hello() print x



6 5



6 6



1.



global



2. 3.



9 (Control flow, Alternatively)

3



Flow of Control



3 1. 2. 3. (Decisions, Choice (Loop Iteration) (Error Checking) Selection)



9.1

9.1.1

scope)



(Decisions, Choice

if Statements

if (True) (False)



Selection)



if (if Statements



51



52 if Condition: Statements ..... ..... else: Statements ..... .....



(Control flow, Flow of Control



Alternatively)



>>> x = 1 >>> if x is 1: >>> print ’Yes’ >>> else: >>> print ’No’ "Yes" True elif ( else if 2 java x "Yes" c/c++) 1 1



if Condition: Statements ..... ..... elif Condition: Statements ..... ..... else: Statements ..... .....



>>> >>> >>> >>> >>> >>> >>>



x = 3 if x 1: print ’x > 1’ else: print ’x = 1’ "x > 1"



9.2



(Loop)



53



9.1.2



switch Statements

switch



9.2

9.2.1



(Loop)

while Statements

while while (while Statements scope)



while Condition: Statements ..... .....



>>> x = 1 >>> while x >> print ’Yes\n’ >>> x+=1



Yes Yes Yes Yes x 1 x True 1 False 1 while x>> for i in range(0, 10): >>> if i % 2 == 0: >>> print i, ’is an even number’ >>> else: >>> print i, ’is an odd number’ 0 0 1 2 3 4 5 6 7 8 9 is is is is is is is is is is an an an an an an an an an an even number odd number even number odd number even number odd number even number odd number even number odd number foreach ach >>> x = {’first’:’one’, ’second’:’two’} >>> for j in x: print x[j] two one for fore9



9.2.3

pass



pass, break, continue



else Clauses Statements



Statements >>> while True: .... pass ....



9.3 break



(Error Checking)



55



continue



else Clauses break (Loop, Iteration)



for n in range(2, 10): for x in range(2, n): if n % x == 0: print n, ’equals’, x, ’*’, n/x break else: print n, ’is a prime number’ 2 3 4 5 6 7 8 9 is a prime is a prime equals 2 * is a prime equals 2 * is a prime equals 2 * equals 3 * number number 2 number 3 number 4 3



9.2.4

2.5 Beta



do-while Statements

do-while ( 24 2549) Python 2.5 Python



9.3

9.3.1 assert Statements



(Error Checking)



assert



assert Condition, ’Text Error or Text Mixed’



56



(Control flow, Flow of Control



Alternatively)



def test(arg1, arg2): arg1 = float(arg1) arg2 = float(arg2) assert arg2 != 0, ’Bad dividend, arg1: %f arg2: %f’ % (arg1, arg2) ratio = arg1 / arg2 print ’ratio:’, ratio test(0,2) test(2,0)



ratio: 0.0 Traceback (most recent call last): File "C:\tmp.py", line 51, in ? test(2,0) File "C:\tmp.py", line 46, in test assert arg2 != 0, ’Bad dividend, arg1: %f arg2: %f’ % (arg1, arg2) AssertionError: Bad dividend, arg1: 2.000000 arg2: 0.000000



9.3.2



try-except



raise Statements (Exception handling)

try-except ,



list error



index if Statements code try-except



null



code code try-except compile try-except error try-except try-except exception try-except



9.3



(Error Checking)



57



try: Standard operation except: Error operation try try except >>> try: ... x = y ... except: ... print ’y not defined’ ... y not defined try-except >>> x = y Traceback (most recent call last): File "", line 1, in ? NameError: name ’y’ is not defined try-except , try-except >>> fridge_contents = {"egg":8, "mushroom":20, "pepper":3, "cheese":2, "tomato":4,"milk":13} >>> if fridge_contents["orange juice"] > 3: ... print "Sure, let’s have some juice" ... Traceback (most recent call last): File "", line 1, in ? KeyError: ’orange juice’ try-except try-except >>> fridge_contents = {"egg":8, "mushroom":20, "pepper":3, "cheese":2, "tomato":4,"milk":13} >>> try: ,



58



(Control flow, Flow of Control



Alternatively)



... if fridge_contents["orange juice"] > 3: ... print "Sure, let’s have some juice" ... except KeyError: ... print "Aww, there’s no juice. Lets go shopping" ... Aww, there’s no juice. Lets go shopping try-except except ror >>> fridge_contents = {"egg":8, "mushroom":20, "pepper":3, "cheese":2, "tomato":4,"milk":13} >>> try: ... if fridge_contents["orange juice"] > 3: ... print "Sure, let’s have some juice" ... except KeyError, error: ... print "Woah! There is no %s" % error ... Woah! There is no ’orange juice’ raise Statements try-except try-except KeyEr-



>>> class E(RuntimeError): ... def __init__(self, msg): ... self.msg = msg ... def getMsg(self): ... return self.msg ... >>> >>> try: ... raise E(’my test error’) ... except E, obj: ... print ’Msg:’, obj.getMsg() ... Msg: my test error



10 (Defined Function)



subroutine )



(Reusability Code) (real function, return value) def



2 (void, sub , subprogram



def function_name( [Argument] ): Statement …… [return]



• function name • Statements • var • Argument • return 1 1



# define def foo(): print "Foobar" # foo()



()



Foobar 59



60



(Defined Function)



10.1

1. 2. 3.



,

(Function Argument) (return) (Function Default Argument)



# define def foo(text): print text # foo("Foobar")



()



Foobar return def add(x,y): return x + y print add(10,20) print add(add(10,20),30) function



30 60



a, b, c = 0, 0, 0 def getabc(): a = "Hello" b = "World" c = "!" return a,b,c def gettuple(): a,b,c = 1,2,3 return (a,b,c) def getlist(): a,b,c = (3,4),(4,5),(5,6) return [a,b,c] a,b,c = getabc()



10.1 print d,e,f print g,h,i print



, a,b,c = gettuple() d,e,f = getlist() g,h,i



61



Hello World ! 1 2 3 (3, 4) (4, 5) (5, 6) x y 0



def add(x = 0,y = 0): return x + y print add(10,20) print add()



30 0



def multiprint( n=5, txt="Hello" ): i = 0 while i 0: while current Run/Stop Error



.6: Output



83



1. Find 2. Browser 3. Recent 4. Todo 5. Index 6. Notes Project Windows Explorer



84



SPE



, Debug

.1 SPE



>>> print "Hello, World!" Source Editor "Tools" ments/Stop" short-key Ctrl+Shift+R menu bar "Run without argu-



.1:



.2:



85



86



, Debug



.2



Debug



.3:



Error



Debug



File "C:\Documents and Settings\Ford AntiTrust\Desktop\helloworld.py", line 1 print "Hello, World! ^ SyntaxError: EOL while scanning single-quoted string Error Error SyntaxError line 1 Output Editor Error Code Systax single-quoted string Interpreter line line 1 Error



File "C:\Documents and Settings\Ford AntiTrust\Desktop\helloworld.py", line 1 column line print



print "Hello, World! ^ SyntaxError: EOL while scanning single-quoted string



• Python programming language. http://www.python.org/, Python Software Foundation, 2006. • Python programming language. http://en.wikipedia.org/wiki/Python programming language, Wikipedia the free encyclopedia, 2006. • Python software. http://en.wikipedia.org/wiki/Python software, Wikipedia the free encyclopedia, 2006. • Comparison of programming languages. http://en.wikipedia.org/wiki/Comparison of programming languages, Wikipedia the free encyclopedia, 2006. • Python Tutorial Online. http://python.cmsthailand.com/, CMSthailand.com, 2005. • An empirical comparison of C, C++, Java, Perl, Python, Rexx, and Tcl — March 2000 ˜ refereed journal paper. http://page.mi.fu-berlin.de/prechelt/Biblio/jccpprt computer2000.pdf, Lutz Prechelt, 2000. • Programming in Python. http://www-128.ibm.com/developerworks/library/os-python5/index.html, Robert Brunner (rb@ncsa.uiuc.edu), Research Scientist, National Center for Supercomputing Applications, 2005. • wxPython, a blending of the wxWidgets C++ class library. http://www.wxpython.org/, OSAF (Open Source Applications Foundation), 2006. • Stani’s Python Editor, Python IDE with Blender, Kiki, PyChecker, wxGlade & XRC support. http://pythonide.stani.be/, S. Michiels, Amsterdam, the Netherlands 2006. • Beginning Python Wiley Publishing, Inc., Peter Norton, Alex Samuel, David Aitel, Eric Foster-Johnson, Leonard Richardson, Jason Diamond, Aleatha Parker, Michael Roberts, 2005. • Python http://veer.exteen.com/, • , 2005.



Python http://plynoi.exteen.com/20060827/python, Plynoi, 2006.



87



64 bit double precision, 30 Alternatively, 50 Category Application Domains, 16 3D Graphics Rendering, 17 Database Access, 16 Desktop GUI, 17 Education, 17 Game, 17 GUI, 17 Network programming, 17 Numeric computation, 17 Scientific, 17 Software builder, 17 Software Testing, 17 Web Internet Development, 16 Colon Symbol, 32 Comment, 22 Concatenation Symbol, 40 Control flow, 50 Data type, 27



(Complex Numbers), 31 (Integer), 29 (Plain Integer), 29 (Long integer), 30 (String Array of Characters), 39



Flow of Control, 50 Function argument, 59 Functions abs(), 26 complex(), 31 float(), 31 int(), 30 len(), 34 max(), 26 min(), 26, 27 print, 21 range(), 27, 53–55 raw input, 63 set(), 35 sum(), 27 type(), 29 (Collection Google, 19 Guido van Rossum, 13 Hello World, 21, 85 Industrial Light & Magic, 18 Language Evaluation Criteria, 15 Cost, 15 Readability, 15 Reliability, 15 Writability, 15 Multi-paradigm language, 15



Data Types), 32 (Dictionary Groupings of Data Indexed by Name), 33 (Tuples) (Sequences), 33 (List), 32 (Array), 32 (Sets), 34 (Numbers), 29 imaginary number, 31 signed integer, 29 (Boolean), 30 (Floating-point numbers), 30



88



89 NASA, 19 Operator *, 25 **, 25, 30 +, 25 -, 25 /, 25 %, 25 Python, 13 Repetition Symbol, 21 Reserved words (Keywords), 22 and, 22, 47 as, 22 assert, 22, 55 break, 22, 54 class, 22 continue, 22, 54 def, 22, 58 del, 22 elif, 22, 51 else, 22, 51 else clauses, 54 else if, 51 except, 22, 56 exec, 22 finally, 22 for, 22, 53 from, 22 global, 22, 49, 62 if, 22, 51 import, 22 in, 22, 45, 53–55 is, 22, 45 lambda, 22 not, 22, 47 or, 22, 47 pass, 22, 54 print, 22 raise, 22, 56 return, 59 return , 22 try, 22, 56 while, 22, 53 with, 22 yield, 22 Stani’s Python Editor (SPE), 75 Browser, 81 Explore, 80 Index, 80 Notes, 80 Source, 81 Editor, 81 Pydoc, 81 Separators, 81 UML view, 81 Todo, 80 Tools, 81 Local object browser, 81 Output, 82 Session, 82 Shell, 81 , 83 , Debug Debug , 86 , 85 SPE, 85 , 80 statement block, statement scope, 48 String Concatenation Symbol, 40 String formatting operator, 41 Symbol *, 21 +, 40 „ 40 :, 32 #, 22 % (String formatting operator), 41 type bool, 30 complex, 31 dict, 33



, 85



90 False, 30 float, 30 int, 29 list, 32 long, 30 set, 34 True, 30 tuple, 34 wxPython, 72 (normal arithmetic operators), 25 , 25 , 25 , 25 , 25 , 25 , 25 , 25 , 22 , 69 , 50 Python, 69 (Error Check- Stani’s Python Editor (SPE), 69, 75 ing), 51, 55 wxPython, 69, 72 assert Statements, 55 (Defined Function), 58 try-except raise Statements (Exception Global Variable, 62 handling), 56 Local Variable, 62 (Decisions, Choice or Selection), (return) , 60 51 (Function Argument), 60 (Decisions, Choice Selec(Function Default Artion) gument, 60 elif, 51 (Comparisons), 43 else, 51 , 45 else if, 51 (Printing) if, 51 19 switch, 52 , 15 (Loop, Iteration), 51 break, 54 , 22 continue, 54 , 27 do-while, 55 , 48 else clauses, 54 (Statement block), 49 for, 53 (Life time Variable swhile, 53 cope), 49 (Arithmetic Mathematics), 23 , 17 (Built-in Math Battlefield 2, 18 Functions), 26 BitTorrent, 17 , 26 Blender, 18 , 27 Chandler, 18 , 26 Civilization IV, 18 , 27 EVE Online, 18 , 27 Indian Ocean Tsunami Detector, 18



,



91 Kombilo, 18 Mailman, 18 MoinMoin, 18 OpenRPG, 18 Plone, 18 Stani’s Python Editor(SPE), 18 Trac, 18 Turbogears, 18 ViewVC, 18 Zope, 18 (Boolean Expressions), 46 AND, 47 NOT, 47 OR, 47 , 13 Python 1.0, 13 Python 2.0, 14 , 14 , 15




Shared by: Blogger2009

Share This Document


Other docs by Blogger2009
Wireless sensor network
Views: 1126  |  Downloads: 115
การติดตั้ง CodeIgniter
Views: 4207  |  Downloads: 62
ตารางสรุปคำสั่ง CSS
Views: 157  |  Downloads: 19
การยกระดับสิทธิ
Views: 53  |  Downloads: 3
คณิตศาสตร์ 2 O-net
Views: 782  |  Downloads: 6
Hacking Web Application
Views: 996  |  Downloads: 14
การขโมยข้อมูล
Views: 345  |  Downloads: 3
Related docs
by registering with docstoc.com you agree to our
privacy policy

You are almost ready to download!

You are almost ready to download!