introduction to python as a functional, object- oriented ...boley/flp/python-intro.pdf ·...

31
0 0 Introduction to Python Introduction to Python as a Functional, as a Functional, Object Object - - Oriented Programming Oriented Programming Language Language Harold Boley, UNB CS, Harold Boley, UNB CS, NRC Semantic Web Laboratory, NRC Semantic Web Laboratory, Fredericton, NB Fredericton, NB January 13, 2005 January 13, 2005 Based on Based on Python Python slides by: slides by: K. Naik, M. Raju and S. K. Naik, M. Raju and S. Bhatkar Bhatkar

Upload: others

Post on 25-May-2020

77 views

Category:

Documents


0 download

TRANSCRIPT

00

Introduction to PythonIntroduction to Pythonas a Functional,as a Functional, ObjectObject--Oriented Programming Oriented Programming

LanguageLanguage

Harold Boley, UNB CS,Harold Boley, UNB CS,NRC Semantic Web Laboratory,NRC Semantic Web Laboratory,

Fredericton, NB Fredericton, NB January 13, 2005January 13, 2005

Based on Based on ““PythonPython”” slides by:slides by:

K. Naik, M. Raju and S. K. Naik, M. Raju and S. BhatkarBhatkar

11

OutlineOutlineIntroductionIntroductionInstallation and UseInstallation and UseDistinct FeaturesDistinct FeaturesPython BasicsPython BasicsFunctionalFunctional ExampleExampleComparisons with Other LanguagesComparisons with Other LanguagesAreas of ApplicationAreas of ApplicationReferencesReferences

22

IntroductionIntroduction

What is Python?What is Python?

•• InterpretedInterpreted•• InteractiveInteractive•• PortablePortable•• FunctionalFunctional•• ObjectObject--OrientedOriented

programming languageprogramming language

33

IntroductionIntroduction

A brief HistoryA brief History

•• Invented in 1990 by Guido Van RossumInvented in 1990 by Guido Van Rossum•• The name The name ‘‘PythonPython’’ stems fromstems from

"Monty Python's Flying Circus""Monty Python's Flying Circus"•• Intended to be a scripting language on Intended to be a scripting language on

Amoeba OSAmoeba OS•• Python was influenced by ABC and Python was influenced by ABC and

ModulaModula--33•• First public release was in 1991First public release was in 1991

44

IntroductionIntroductionGoalsGoals

•• Designed to be simple yet powerfulDesigned to be simple yet powerful•• Allow modular programmingAllow modular programming•• Great emphasis on readabilityGreat emphasis on readability•• Rapid application development Rapid application development •• Easy to embed in and extend with other Easy to embed in and extend with other

languages languages

55

IntroductionIntroduction(Web) Applications(Web) Applications

•• Google Google PageRankPageRank algorithmalgorithm and and Interfaces to Interfaces to the Google APIthe Google API

•• Tim BernersTim Berners--LeeLee’’s generals general--purpose data purpose data processor, processor, cwmcwm, for the Semantic Web, for the Semantic Web

•• Scripts for Scripts for ‘‘gluinggluing’’ NRC subsystems, e.g. within NRC subsystems, e.g. within inDiscoverinDiscover, as, as pioneered by Daniel pioneered by Daniel LemireLemire

•• More: More: Python Package Index Python Package Index

66

Installation and UseInstallation and Use

Freely available at Freely available at http://www.python.org/downloadhttp://www.python.org/downloadYou can download the appropriate You can download the appropriate installation for your computerinstallation for your computerCan be used in both interactive andCan be used in both interactive andbatch modebatch modeIDLE is the editor for writing and running IDLE is the editor for writing and running Python Python programsprograms

77

Distinct FeaturesDistinct Features

Extensible (packages)Extensible (packages)Embeddable into applicationsEmbeddable into applicationsFunctional Functional programmingprogrammingObjectObject--Oriented Oriented programmingprogrammingRapid PrototypingRapid PrototypingGreat for readability and presentationGreat for readability and presentationWhite space is significantWhite space is significantLow maintenance costs Low maintenance costs Exception handlingException handlingFree (open source)Free (open source)

88

Python BasicsPython Basics

BuiltBuilt--in data structuresin data structuresNumbersNumbers•• decimal decimal e.g.e.g. 631, 3.14631, 3.14•• octal octal e.g.e.g. O631O631•• hexadecimalhexadecimal e.ge.g. . oxABCoxABC•• complexcomplex e.ge.g.. 1 + 3j1 + 3j•• longlong e.ge.g.. 122233445656455L122233445656455L

•• Normal Arithmetic and Bit operatorsNormal Arithmetic and Bit operators•• Integer division truncates e.g. 1/2 = 0Integer division truncates e.g. 1/2 = 0

99

Python BasicsPython BasicsStringsStrings•• Concatenation Concatenation

““HelloHello”” + + ““WorldWorld”” --> > ““HelloWorldHelloWorld””•• RepetitionRepetition

““UMBCUMBC”” * 3* 3 --> > ““UMBCUMBCUMBCUMBCUMBCUMBC””•• Indexing Indexing

““UMBCUMBC””[0][0] --> > ““UU””•• SlicingSlicing

““UMBCUMBC””[1:3][1:3] --> > ““MBMB””•• Size Size

len(len(““UMBCUMBC””)) --> 4> 4

1010

Python BasicsPython Basics

•• Comparison Comparison ““UMBCUMBC”” < < ““umbcumbc”” --> 0> 0

•• Search Search ““MM”” in in ““UMBCUMBC”” --> 1> 1

•• Can also be enclosed in single quotesCan also be enclosed in single quotese.g. e.g. ‘‘UMBCUMBC’’

1111

Python BasicsPython Basics

ListsLists•• e.g. e.g.

aList = [631, aList = [631, ““Programming languagesProgramming languages””, , [331, [331, ““programming languagesprogramming languages””]]]]

•• List items need not have the same typeList items need not have the same type•• Like Like indexableindexable arrays, not Lisparrays, not Lisp--like linked listlike linked list•• Extended at right end, not LispExtended at right end, not Lisp--like at left end:like at left end:

tail.append(headtail.append(head), not ), not cons(head,tailcons(head,tail))•• Same operators as for stringsSame operators as for strings•• More operations append(), insert(), pop(), More operations append(), insert(), pop(),

reverse() and sort()reverse() and sort()

1212

Python BasicsPython Basics

TuplesTuples•• E.g.E.g.

aTuple = (631, aTuple = (631, ““Programming LanguagesProgramming Languages””, , (611, (611, ““Computer ArchitectureComputer Architecture””))))

•• Nesting is PossibleNesting is Possible•• Outer Parentheses are optionalOuter Parentheses are optional•• Unlike lists and like strings tuples are immutableUnlike lists and like strings tuples are immutable

1313

Python BasicsPython BasicsDictionaries (cf. Lisp property lists, RDF, ...)Dictionaries (cf. Lisp property lists, RDF, ...)•• E.g.E.g.

Map = {Map = {““GuidoGuido””: : ““PythonPython””, , ““MilnerMilner””: : ““MLML””}}

•• Lookup Lookup Map[Map[““GuidoGuido””]] returns returns ““PythonPython””Map[Map[““MilnerMilner””]] returns returns ““MLML””

•• InsertInsert Map[Map[““RitchieRitchie””] = ] = ““CC””•• Delete Delete del Map[del Map[““MilnerMilner””]]•• Iterations Iterations keys() values() items()keys() values() items()•• Presence Presence has_key(has_key(““GuidoGuido””))

•• Values could be anythingValues could be anything•• Keys must be immutableKeys must be immutable

1414

Python BasicsPython Basics

VariablesVariables

•• No need to declareNo need to declare•• Not typedNot typed

E.g. F = 2 * 4.5E.g. F = 2 * 4.5•• Need to initializeNeed to initialize•• Almost everything can be assigned to a variable Almost everything can be assigned to a variable

(functions, modules, classes)(functions, modules, classes)

1515

Python BasicsPython BasicsReferencesReferences

•• a = b does not make copy of ba = b does not make copy of b•• b = a, a and b refer to the same objectb = a, a and b refer to the same object

E.g.E.g.>>> a = [1,2,3] >>> a = [1,2,3] >>> b = a >>> b = a >>> a.append(4)>>> a.append(4)>>> print b>>> print b[1, 2, 3, 4][1, 2, 3, 4]

1616

Python BasicsPython BasicsFlow of ControlFlow of Control•• if condition : statementsif condition : statements

((elifelif condition : statements)*condition : statements)*[else : statements][else : statements]

•• while condition : statementswhile condition : statements

•• for var in sequence : statementsfor var in sequence : statements

•• breakbreak•• continuecontinue

1717

Python BasicsPython Basics

An ExampleAn Example

(Fibonacci series)(Fibonacci series)

>>> a = 0>>> a = 0>>> b = 1>>> b = 1>>> while b < 1000>>> while b < 1000…… print bprint b…… a, b = b, a + ba, b = b, a + b

1818

Python BasicsPython BasicsProcedures and FunctionsProcedures and Functions•• General Form General Form def(arg1, arg2, def(arg1, arg2, ……))

StatementsStatementsreturnreturn # from procedure# from procedure ORORreturn expressionreturn expression # from function# from function

ProceduresProcedures can omit any can omit any ‘‘returnreturn’’E.g.E.g.

•• >>> def >>> def fibproc(nfibproc(n): # write Fibonacci series up to n): # write Fibonacci series up to n•• ... """Print a Fibonacci series up to n."""... """Print a Fibonacci series up to n."""•• ... a, b = 0, 1... a, b = 0, 1•• ... while b < n:... while b < n:•• ... print b,... print b,•• ... a, b = b, a+b... a, b = b, a+b•• ... ... •• >>> >>> fibprocfibproc(1000) (1000) # calling the # calling the procedureprocedure•• 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 9871 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

1919

Python BasicsPython BasicsPure FunctionsPure Functions•• It is simple to write a function that returns a list of the numbIt is simple to write a function that returns a list of the numbersers

of the Fibonacci series, instead of a of the Fibonacci series, instead of a procedureprocedure printing them:printing them:

•• >>> def >>> def fibfun(nfibfun(n): # return Fibonacci series up to n): # return Fibonacci series up to n•• ... """Return a list containing the Fibonacci series up to n.""... """Return a list containing the Fibonacci series up to n.""""•• ... result = []... result = []•• ... a, b = 0, 1... a, b = 0, 1•• ... while b < n:... while b < n:•• ... ... result.append(bresult.append(b))•• ... ... a, b = b, a, b = b, a+ba+b•• ... return result... return result•• ......•• >>> >>> fibfunfibfun (1000) # calling the function (1000) # calling the function

•• [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987][1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]

2020

Python BasicsPython Basics

ModulesModules

•• A module is a file containing Python definitions A module is a file containing Python definitions and statementsand statements

•• File should have suffix .pyFile should have suffix .py•• Within a module, the moduleWithin a module, the module’’s name is s name is

available as through global variable _name_.available as through global variable _name_.•• Use Use ““import moduleimport module--namename”” to import the to import the

functions in this modulefunctions in this module•• It is not required to place all import It is not required to place all import

statements at the beginning of a modulestatements at the beginning of a module•• Some modules are builtSome modules are built--in e.g. sysin e.g. sys

2121

Python BasicsPython BasicsPackagesPackages

•• Structure PythonStructure Python’’s module namespace using s module namespace using dotted module namesdotted module names

•• E.g. A.B.C refers to the submodule C of E.g. A.B.C refers to the submodule C of module B in package Amodule B in package A

•• To import module C To import module C --> > ““import A.B.Cimport A.B.C”” and use the fully qualified name ORand use the fully qualified name OR““from A.B import Cfrom A.B import C”” and use only the module nameand use only the module name

•• Subpackages need to use fully qualified names Subpackages need to use fully qualified names to refer to each otherto refer to each other

2222

Python BasicsPython BasicsClassesClassesE.g.E.g.

class ClassName:class ClassName:statements statements OROR

class ClassName(BaseClass1, BaseClass2class ClassName(BaseClass1, BaseClass2……))statementsstatements

ObjectsObjectsx = ClassName() creates a new instance of x = ClassName() creates a new instance of

class class ClassNameClassName and assigns it to the variable xand assigns it to the variable x

2323

Python BasicsPython BasicsAn ExampleAn Example

class stack:class stack:““A well known data structure.A well known data structure.””def __init__(self) :def __init__(self) : #constructor#constructor

self.items = []self.items = []def push(self, x) :def push(self, x) :

self.items.append(x)self.items.append(x)def pop(self) :def pop(self) :

x = self.items[x = self.items[--1]1]del self.items[del self.items[--1]1]return xreturn x

def empty(self)def empty(self)return len(self.items) == 0return len(self.items) == 0

2424

FunctionalFunctional ExampleExamplePure function returning index of Pure function returning index of itemitem in in datadata

def binarySearch(data, item):def binarySearch(data, item):min = 0; max = len(data) min = 0; max = len(data) -- 11while 1:while 1:

if max < min:if max < min:return return ““notnot--foundfound””

m = (min + max) / 2m = (min + max) / 2if item > if item > data[mdata[m]:]:

min = m + 1min = m + 1elifelif item < item < data[mdata[m]:]:

max = m max = m -- 11else:else:

return mreturn m

2525

ComparisonsComparisonsVs perlVs perl•• Easier to learnEasier to learn•• More readableMore readable•• Fewer side effectsFewer side effects•• Less Unix biasLess Unix bias

Vs TclVs Tcl•• Much fasterMuch faster•• Less need for C extensionsLess need for C extensions•• Better java integrationBetter java integration

2626

ComparisonsComparisons

Vs javaVs java

•• More concise codeMore concise code•• Dynamic typingDynamic typing•• Runs slower but development is fastRuns slower but development is fast•• No nativeNo native--code compilationcode compilation•• Can be integrated with java using Can be integrated with java using JPythonJPython

2727

ComparisonsComparisons

Vs lispVs lisp•• Indexed arrays instead of linked listsIndexed arrays instead of linked lists•• WhitespaceWhitespace instead of parentheses instead of parentheses ☺☺

•• Compiler still (much) slower: Compiler still (much) slower: bytecodebytecode onlyonly

•• More: More: http://www.norvig.com/pythonhttp://www.norvig.com/python--lisp.htmllisp.html

Vs Vs relfunrelfun•• Mutable objects instead of logical relationsMutable objects instead of logical relations•• More: More: http://http://www.cs.unb.ca/~boley/FLPwww.cs.unb.ca/~boley/FLP

2828

Comparisons Comparisons ── ExampleExample

pythonpythondef fac(n):

if n==0: return 1else: return fac(n-1) * n

relfunrelfunfac(0) :& 1.fac(N) :& *(fac(-(N,1)), N).

2929

Areas of ApplicationAreas of Application

Glue languageGlue languageGraphical applicationsGraphical applicationsDatabase applicationsDatabase applicationsMultimedia applicationsMultimedia applicationsInternet protocol applicationsInternet protocol applicationsWeb (scripting) applications: see aboveWeb (scripting) applications: see above

3030

ReferencesReferences

Python HomepagePython Homepage•• http://www.python.org/http://www.python.org/

Python TutorialPython Tutorial•• http://www.python.org/tuthttp://www.python.org/tut

Python documentationPython documentation•• http://www.python.org/dochttp://www.python.org/doc