introduction to python programming languages fall 2003 adapted from tutorial by mark hammond...
Post on 21-Dec-2015
223 views
TRANSCRIPT
Introduction to PythonIntroduction to PythonProgramming LanguagesProgramming Languages
Fall 2003Fall 2003
Adapted from Tutorial byAdapted from Tutorial by
Mark HammondMark Hammond
Skippi-Net, Melbourne, Skippi-Net, Melbourne, AustraliaAustralia
[email protected]@skippinet.com.auu
http://starship.python.net/crew/http://starship.python.net/crew/mhammondmhammond
What Is Python?What Is Python?
Created in 1990 by Guido van RossumCreated in 1990 by Guido van RossumWhile at CWI, AmsterdamWhile at CWI, AmsterdamNow hosted by centre for national Now hosted by centre for national
research initiatives, Reston, VA, USAresearch initiatives, Reston, VA, USAFree, open sourceFree, open source
And with an amazing communityAnd with an amazing communityObject oriented languageObject oriented language
““Everything is an object”Everything is an object”
Why Python?Why Python?Designed to be easy to learn and masterDesigned to be easy to learn and master
Clean, clear syntaxClean, clear syntaxVery few keywordsVery few keywords
Highly portableHighly portableRuns almost anywhere - high end servers and Runs almost anywhere - high end servers and
workstations, down to windows CEworkstations, down to windows CEUses machine independent byte-codesUses machine independent byte-codes
ExtensibleExtensibleDesigned to be extensible using C/C++, Designed to be extensible using C/C++,
allowing access to many external librariesallowing access to many external libraries
Python: a modern hybridPython: a modern hybrid
A language for scripting and prototypingA language for scripting and prototypingBalance between extensibility and Balance between extensibility and
powerful built-in data structurespowerful built-in data structuresgenealogy:genealogy:
Setl (NYU, J.Schwartz et al. 1969-1980)Setl (NYU, J.Schwartz et al. 1969-1980)ABC (Amsterdam, Meertens et al. ABC (Amsterdam, Meertens et al.
1980-)1980-)Python (Van Rossum et all. 1996-)Python (Van Rossum et all. 1996-)
Very active open-source communityVery active open-source community
PrototypingPrototyping
Emphasis on experimental programming:Emphasis on experimental programming: Interactive Interactive (like LISP, ML, etc).(like LISP, ML, etc).Translation to bytecode Translation to bytecode (like Java)(like Java)Dynamic typing Dynamic typing (like LISP, SETL, APL)(like LISP, SETL, APL)Higher-order function Higher-order function (LISP, ML)(LISP, ML)Garbage-collected, no ptrsGarbage-collected, no ptrs
(LISP, SNOBOL4)(LISP, SNOBOL4)
PrototypingPrototyping
Emphasis on experimental Emphasis on experimental programming:programming:
Uniform treatment of indexable Uniform treatment of indexable structures structures (like SETL)(like SETL)
Built-in Built-in associative structuresassociative structures (like SETL, SNOBOL4, Postscript)(like SETL, SNOBOL4, Postscript)
Light syntax, indentation is Light syntax, indentation is significant significant (from ABC)(from ABC)
Most obvious and notorious Most obvious and notorious featuresfeatures
Clean syntax plus high-level data Clean syntax plus high-level data typestypesLeads to fast codingLeads to fast coding
Uses white-space to delimit blocksUses white-space to delimit blocksHumans generally do, so why not the Humans generally do, so why not the
language?language?Try it, you will end up liking itTry it, you will end up liking it
Variables do not need declarationVariables do not need declarationAlthough not a type-less languageAlthough not a type-less language
A Digression on Block A Digression on Block StructureStructure
There are three ways of dealing with There are three ways of dealing with IF structuresIF structuresSequences of statements with explicit Sequences of statements with explicit
end (Algol-68, Ada, COBOL)end (Algol-68, Ada, COBOL)Single statementSingle statement
(Algol-60, Pascal, C)(Algol-60, Pascal, C)Indentation (ABC, Python)Indentation (ABC, Python)
Sequence of StatementsSequence of Statements
IF condition THENIF condition THENstm;stm;stm;stm;....
ELSIF condition THENELSIF condition THENstm;stm;....
ELSEELSEstm;stm;....
END IF;END IF;next statement;next statement;
Single StatementSingle Statement IF condition THENIF condition THEN
BEGINBEGIN stm; stm;
stm; stm;ENDEND ....
ELSE IF condition THENELSE IF condition THENBEGINBEGIN stm; stm; ....END;END;
ELSEELSEBEGINBEGINstm;stm;....END;END;
next-statement;next-statement;
IndentationIndentation
IF condition:IF condition: stm;stm;
stm;stm;....
ELSIF condition:ELSIF condition:stm;stm;....
ELSE:ELSE:stm;stm;....
next-statementnext-statement
PythonwinPythonwin
These examples use PythonwinThese examples use PythonwinOnly available on WindowsOnly available on WindowsGUI toolkit using Tkinter available for GUI toolkit using Tkinter available for
most platformsmost platformsStandard console Python available on all Standard console Python available on all
platformsplatformsHas interactive mode for quick Has interactive mode for quick
testing of codetesting of code Includes debugger and Python editorIncludes debugger and Python editor
Interactive PythonInteractive Python
Starting Python.exe, or any of the GUI Starting Python.exe, or any of the GUI environments present an interactive environments present an interactive modemode>>>>>> prompt indicates start of a prompt indicates start of a
statement or expressionstatement or expression
If incomplete, If incomplete, ...... prompt indicates prompt indicates second and subsequent linessecond and subsequent lines
All expression results printed back to All expression results printed back to interactive consoleinteractive console
Variables and TypesVariables and Types (1 of 3) (1 of 3)
Variables need no declarationVariables need no declaration>>> a=1>>> a=1>>>>>>
As a variable assignment is a As a variable assignment is a statement, there is no printed resultstatement, there is no printed result
>>> a>>> a11
Variable name alone is an expression, Variable name alone is an expression, so the result is printedso the result is printed
Variables and Types Variables and Types (2 of 3)(2 of 3)
Variables must be created before they Variables must be created before they can be usedcan be used
>>> b>>> bTraceback (innermost last):Traceback (innermost last): File "<interactive input>", line 1, File "<interactive input>", line 1, in ?in ?NameError: bNameError: b>>>>>>
Python uses exceptions - more detail Python uses exceptions - more detail laterlater
Variables and Types Variables and Types (3 of 3)(3 of 3)
Objects always have a typeObjects always have a type>>> a = 1>>> a = 1>>> type(a)>>> type(a)<type 'int'> <type 'int'> >>> a = "Hello">>> a = "Hello">>> type(a)>>> type(a)<type 'string'><type 'string'>>>> type(1.0)>>> type(1.0)<type 'float'><type 'float'>
Assignment versus Equality Assignment versus Equality TestingTesting
Assignment performed with single =Assignment performed with single =Equality testing done with double = (==)Equality testing done with double = (==)
Sensible type promotions are definedSensible type promotions are definedIdentity tested with Identity tested with isis operator. operator.
>>> 1==1>>> 1==111>>> 1.0==1>>> 1.0==111>>> "1"==1>>> "1"==100
Simple Data TypesSimple Data Types
StringsStringsMay hold any data, including embedded May hold any data, including embedded
NULLsNULLsDeclared using either single, double, or triple Declared using either single, double, or triple
quotesquotes>>> s = "Hi there">>> s = "Hi there">>> s>>> s'Hi there''Hi there'>>> s = "Embedded 'quote'">>> s = "Embedded 'quote'">>> s>>> s"Embedded 'quote'""Embedded 'quote'"
Simple Data TypesSimple Data Types
Triple quotes useful for multi-line stringsTriple quotes useful for multi-line strings>>> s = """ a long>>> s = """ a long... string with "quotes" or ... string with "quotes" or anything else"""anything else""">>> s>>> s' a long\012string with "quotes" ' a long\012string with "quotes" or anything else' or anything else' >>> len(s)>>> len(s)4545
Simple Data TypesSimple Data Types Integer objects implemented using C Integer objects implemented using C
longslongsLike C, integer division returns the floorLike C, integer division returns the floor>>> 5/2>>> 5/222
Float types implemented using C Float types implemented using C doublesdoublesNo point in having single precision since No point in having single precision since
execution overhead is large anywayexecution overhead is large anyway
Simple Data TypesSimple Data Types
Long Integers have unlimited sizeLong Integers have unlimited sizeLimited only by available memoryLimited only by available memory>>> long = 1L << 64>>> long = 1L << 64>>> long ** 5>>> long ** 5213598703592091008239502170616955211460270452221359870359209100823950217061695521146027045223566527699470416078222197257806405500229620869356652769947041607822219725780640550022962086936576L36576L
High Level Data TypesHigh Level Data Types
Lists hold a sequence of itemsLists hold a sequence of itemsMay hold any objectMay hold any objectDeclared using square bracketsDeclared using square brackets
>>> l = []# An empty list>>> l = []# An empty list>>> l.append(1)>>> l.append(1)>>> l.append("Hi there")>>> l.append("Hi there")>>> len(l)>>> len(l)22
High Level Data TypesHigh Level Data Types
>>> l>>> l[1, 'Hi there'][1, 'Hi there']>>>>>>>>> l = ["Hi there", 1, 2]>>> l = ["Hi there", 1, 2]>>> l>>> l['Hi there', 1, 2]['Hi there', 1, 2]>>> l.sort()>>> l.sort()>>> l>>> l[1, 2, 'Hi there'][1, 2, 'Hi there']
High Level Data TypesHigh Level Data Types
Tuples are similar to listsTuples are similar to listsSequence of itemsSequence of itemsKey difference is they are immutableKey difference is they are immutableOften used in place of simple structuresOften used in place of simple structures
Automatic unpackingAutomatic unpacking>>> point = 2,3>>> point = 2,3>>> x, y = point>>> x, y = point>>> x>>> x22
High Level Data TypesHigh Level Data Types
Tuples are particularly useful to Tuples are particularly useful to return multiple values from a return multiple values from a functionfunction
>>> x, y = GetPoint()>>> x, y = GetPoint()As Python has no concept of byref As Python has no concept of byref
parameters, this technique is used parameters, this technique is used widelywidely
High Level Data TypesHigh Level Data Types
Dictionaries hold key-value pairsDictionaries hold key-value pairsOften called maps or hashes. Often called maps or hashes.
Implemented using hash-tablesImplemented using hash-tablesKeys may be any immutable object, Keys may be any immutable object,
values may be any objectvalues may be any objectDeclared using bracesDeclared using braces
>>> d={}>>> d={}>>> d[0] = "Hi there">>> d[0] = "Hi there">>> d["foo"] = 1>>> d["foo"] = 1
High Level Data TypesHigh Level Data Types
Dictionaries (cont.)Dictionaries (cont.) >>> len(d)>>> len(d)22>>> d[0]>>> d[0]'Hi there''Hi there'>>> d = {0 : "Hi there", 1 : >>> d = {0 : "Hi there", 1 : "Hello"}"Hello"}>>> len(d)>>> len(d)22
BlocksBlocks
Blocks are delimited by indentationBlocks are delimited by indentationColon used to start a blockColon used to start a blockTabs or spaces may be usedTabs or spaces may be usedMixing tabs and spaces works, but is Mixing tabs and spaces works, but is
discourageddiscouraged>>> if 1:>>> if 1:... ... print "True"print "True"... ... TrueTrue>>>>>>
BlocksBlocks
Many hate this when they first see itMany hate this when they first see itMost Python programmers come to love itMost Python programmers come to love it
Humans use indentation when reading Humans use indentation when reading code to determine block structurecode to determine block structureEver been bitten by the C code?:Ever been bitten by the C code?:
if (1)if (1) printf("True"); printf("True"); CallSomething(); CallSomething();
LoopingLooping
The The forfor statement loops over sequences statement loops over sequences>>> for ch in "Hello":>>> for ch in "Hello":... ... print chprint ch... ... HHeelllloo>>> >>>
LoopingLooping
Built-in function Built-in function range()range() used to used to build sequences of integersbuild sequences of integers
>>> for i in range(3):>>> for i in range(3):... print i... print i... ... 001122>>> >>>
LoopingLooping
whilewhile statement for more traditional statement for more traditional loopsloops
>>> i = 0>>> i = 0>>> while i < 2:>>> while i < 2:... print i... print i... i = i + 1... i = i + 1... ... 0011>>> >>>
FunctionsFunctions
Functions are defined with the Functions are defined with the defdef statement:statement:
>>> def foo(bar):>>> def foo(bar):... return bar... return bar>>> >>>
This defines a trivial function named This defines a trivial function named foofoo that takes a single parameter that takes a single parameter barbar
FunctionsFunctions
A function definition simply places a A function definition simply places a function object in the namespacefunction object in the namespace
>>> foo>>> foo<function foo at fac680><function foo at fac680>
>>>>>> And the function object can obviously And the function object can obviously
be called:be called: >>> foo(3)>>> foo(3)33>>>>>>
ClassesClasses
Classes are defined using the Classes are defined using the classclass statementstatement
>>> class Foo:>>> class Foo:... def __init__(self):... def __init__(self):... self.member = 1... self.member = 1... def GetMember(self):... def GetMember(self):... return self.member... return self.member... ... >>> >>>
ClassesClasses
A few things are worth pointing out in the A few things are worth pointing out in the previous example:previous example:The constructor has a special name The constructor has a special name __init____init__, while a destructor (not shown) , while a destructor (not shown) uses uses __del____del__
The The selfself parameter is the instance (ie, the parameter is the instance (ie, the thisthis in C++). In Python, the self parameter in C++). In Python, the self parameter is explicit (c.f. C++, where it is implicit) is explicit (c.f. C++, where it is implicit)
The name The name selfself is not required - simply a is not required - simply a conventionconvention
ClassesClasses
Like functions, a class statement simply Like functions, a class statement simply adds a class object to the namespaceadds a class object to the namespace
>>> Foo>>> Foo<class __main__.Foo at 1000960><class __main__.Foo at 1000960>>>>>>>
Classes are instantiated using call syntaxClasses are instantiated using call syntax >>> f=Foo()>>> f=Foo()>>> f.GetMember()>>> f.GetMember()11
ModulesModules
Most of Python’s power comes from Most of Python’s power comes from modulesmodules
Modules can be implemented either in Modules can be implemented either in Python, or in C/C++Python, or in C/C++
importimport statement makes a module statement makes a module availableavailable
>>> import string>>> import string>>> string.join( ["Hi", "there"] )>>> string.join( ["Hi", "there"] )'Hi there''Hi there'>>>>>>
ExceptionsExceptions
Python uses exceptions for errorsPython uses exceptions for errorstrytry / / exceptexcept block can handle block can handle
exceptionsexceptions >>> try:>>> try:... 1/0... 1/0... except ZeroDivisionError:... except ZeroDivisionError:... print "Eeek"... print "Eeek"... ... EeekEeek>>> >>>
ExceptionsExceptions
trytry / / finallyfinally block can guarantee block can guarantee execute of code even in the face of execute of code even in the face of exceptionsexceptions
>>> try:>>> try:... 1/0... 1/0... finally:... finally:... print "Doing this anyway"... print "Doing this anyway"... ... Doing this anywayDoing this anywayTraceback (innermost last): File "<interactive Traceback (innermost last): File "<interactive input>", line 2, in ?input>", line 2, in ?ZeroDivisionError: integer division or moduloZeroDivisionError: integer division or modulo>>>>>>
ThreadsThreadsNumber of ways to implement threadsNumber of ways to implement threadsHighest level interface modelled after Highest level interface modelled after
JavaJava >>> class DemoThread(threading.Thread):>>> class DemoThread(threading.Thread):
... def run(self):... def run(self):
... for i in range(3):... for i in range(3):
... time.sleep(3)... time.sleep(3)
... print i... print i
... ... >>> t = DemoThread()>>> t = DemoThread()>>> t.start()>>> t.start()>>> t.join()>>> t.join()001 1 <etc><etc>
Standard LibraryStandard Library
Python comes standard with a set of Python comes standard with a set of modules, known as the “standard library”modules, known as the “standard library”
Incredibly rich and diverse functionality Incredibly rich and diverse functionality available from the standard libraryavailable from the standard libraryAll common internet protocols, sockets, CGI, All common internet protocols, sockets, CGI,
OS services, GUI services (via Tcl/Tk), OS services, GUI services (via Tcl/Tk), database, Berkeley style databases, calendar, database, Berkeley style databases, calendar, Python parser, file globbing/searching, Python parser, file globbing/searching, debugger, profiler, threading and debugger, profiler, threading and synchronisation, persistency, etcsynchronisation, persistency, etc
External libraryExternal library
Many modules are available externally Many modules are available externally covering almost every piece of covering almost every piece of functionality you could ever desirefunctionality you could ever desireImaging, numerical analysis, OS specific Imaging, numerical analysis, OS specific
functionality, SQL databases, Fortran functionality, SQL databases, Fortran interfaces, XML, Corba, COM, Win32 API, interfaces, XML, Corba, COM, Win32 API, etc etc
Way too many to give the list any Way too many to give the list any justicejustice
Python ProgramsPython ProgramsPython programs and modules are Python programs and modules are
written as text files with traditionally written as text files with traditionally a a .py.py extension extension
Each Python module has its own Each Python module has its own discrete namespacediscrete namespace
Name space within a Python module Name space within a Python module is a global one.is a global one.
Python ProgramsPython ProgramsPython modules and programs are Python modules and programs are
differentiated only by the way they differentiated only by the way they are calledare called.py files executed directly are programs .py files executed directly are programs
(often referred to as scripts)(often referred to as scripts).py files referenced via the .py files referenced via the importimport
statement are modulesstatement are modules
Python ProgramsPython Programs
Thus, the same .py file can be a Thus, the same .py file can be a program/script, or a moduleprogram/script, or a module
This feature is often used to provide This feature is often used to provide regression tests for modulesregression tests for modulesWhen module is executed as a program, When module is executed as a program,
the regression test is executedthe regression test is executedWhen module is imported, test When module is imported, test
functionality is not executedfunctionality is not executed
More Information on PythonMore Information on Python
Can’t do Python justice in this short time Can’t do Python justice in this short time frameframeBut hopefully have given you a taste of the But hopefully have given you a taste of the
languagelanguageComes with extensive documentation, Comes with extensive documentation,
including tutorials and library referenceincluding tutorials and library referenceAlso a number of Python books availableAlso a number of Python books available
Visit Visit www.python.orgwww.python.org for more details for more detailsCan find python tutorial and reference Can find python tutorial and reference
manualmanual
Scripting LanguagesScripting Languages
What are they?What are they?Beats me Beats me Apparently they are programming Apparently they are programming
languages used for building the languages used for building the equivalent of shell scripts, i.e. doing the equivalent of shell scripts, i.e. doing the sort of things that shell scripts have sort of things that shell scripts have traditionally been used for.traditionally been used for.
But any language can be used this wayBut any language can be used this waySo it is a matter of convenienceSo it is a matter of convenience
Characteristics of Scripting Characteristics of Scripting LanguagesLanguages
Typically interpretiveTypically interpretiveBut that’s an implementation detailBut that’s an implementation detail
Typically have high level data structuresTypically have high level data structuresBut rich libraries can substitute for thisBut rich libraries can substitute for thisFor example, look at GNAT.SpitbolFor example, look at GNAT.Spitbol
Powerful flexible string handlingPowerful flexible string handlingTypically have rich librariesTypically have rich libraries
But any language can meet this requirementBut any language can meet this requirement
Is Python A Scripting Is Python A Scripting Language?Language?
Usually thought of as oneUsually thought of as oneBut this is mainly a marketing issueBut this is mainly a marketing issue
People think of scripting languages as People think of scripting languages as being easy to learn, and useful.being easy to learn, and useful.
But Python is a well worked out But Python is a well worked out coherent dynamic programming coherent dynamic programming languagelanguageAnd there is no reason not to use it for a And there is no reason not to use it for a
wide range of applications.wide range of applications.