An Introduction To The Python Programming Language

Transcription

Introduction Python Tutorial Numerics & Plotting Standard libraryAn introduction to the Python programminglanguagePrabhu RamachandranDepartment of Aerospace EngineeringIIT BombayJanuary 16, 2007Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryOutline1IntroductionIntroduction to Python2Python TutorialPreliminariesData typesControl flow, functionsModules, exceptions, classesMiscellaneous3Numerics & PlottingNumPy ArraysPlotting: MatplotlibSciPy4Standard libraryQuick TourPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryIntroduction to PythonOutline1IntroductionIntroduction to Python2Python TutorialPreliminariesData typesControl flow, functionsModules, exceptions, classesMiscellaneous3Numerics & PlottingNumPy ArraysPlotting: MatplotlibSciPy4Standard libraryQuick TourPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryIntroduction to PythonIntroductionCreator and BDFL: Guido van RossumBDFL Benevolent Dictator For LifeConceived in December 1989The name “Python”: Monty Python’s Flying CircusCurrent stable version of Python is 2.5.xPSF license (like BSD: no strings attached)Highly cross platformRuns on the Nokia series 60!Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryIntroduction to PythonResourcesAvailable as part of any sane GNU/Linux distributionWeb: http://www.python.orgDocumentation: http://www.python.org/docFree Tutorials:Official Python tutorial:http://docs.python.org/tut/tut.htmlByte of Python: http://www.byteofpython.info/Dive into Python: http://diveintopython.org/Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryIntroduction to PythonWhy Python?High level, interpreted, modular, OOEasy to learnEasy to read codeMuch faster development cyclePowerful interactive interpreterRapid application developmentPowerful standard libraryInterfaces well to C , C and FORTRAN librariesIn short: there is little you can’t do with itPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryIntroduction to PythonA quoteI came across Python and its Numerical extension in1998 . . . I quickly fell in love with Python programmingwhich is a remarkable statement to make about aprogramming language. If I had not seen others with thesame view, I might have seriously doubted my sanity.– Travis Oliphant (creator of NumPy)Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryIntroduction to PythonWhy not ***lab?Open Source, FreePortablePython is a real programming language: large and smallprogramsCan do much more than just array and mathWrap large C codesBuild large code bases via SConsInteractive data analysis/plottingParallel applicationJob scheduling on a custom clusterMiscellaneous scriptsPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryIntroduction to PythonWhy not Python?Can be slow for high-performance applicationsThis can be fairly easily overcome by using C/C /FORTRANextensionsPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryIntroduction to PythonUse casesNASA: Python Streamlines Space Shuttle Mission DesignAstraZeneca Uses Python for Collaborative Drug DiscoveryForecastWatch.com Uses Python To Help MeteorologistsIndustrial Light & Magic Runs on PythonZope: Commercial grade CMSRedHat: install scripts, sys-admin toolsNumerous success stories:http://www.pythonology.com/successPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryIntroduction to PythonBefore we beginThis is only an introductionPython is a full-fledged programming languagePlease read the tutorialIt is very well written and can be read in one afternoonPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousOutline1IntroductionIntroduction to Python2Python TutorialPreliminariesData typesControl flow, functionsModules, exceptions, classesMiscellaneous3Numerics & PlottingNumPy ArraysPlotting: MatplotlibSciPy4Standard libraryQuick TourPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousPreliminaries: The InterpreterPython is interpretedInterpreted vs. CompiledInterpreted languages allow for rapid testing/prototypingDynamically typedFull introspection of code at runtimeDid I say dynamic?Does not force OO or a particular programming paradigmdown your throat!Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousPreliminaries: IPythonRecommended interpreter, IPython:http://ipython.scipy.orgBetter than the default Python shellSupports tab completion by defaultEasier object introspectionShell access!Command system to allow extending its own behaviorSupports history (across sessions) and loggingCan be embedded in your own Python codeSupport for macrosA flexible framework for your own custom interpreterOther miscellaneous conveniencesWe’ll get back to this laterPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousPreliminaries . . .Will follow the Official Python tutorialNo lexical blockingIndentation specifies scopeLeads to easier to read code!Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousUsing the interpreterStarting up: python or ipythonQuitting: Control-D or Control-Z (on Win32)Can use it like a calculatorCan execute one-liners via the -c option: python -c"print ’hello world’"Other options via python -hPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousBasic conceptsDynamically typedAssignments need not specify a typeaaaa 11.1" foo "SomeClass ( )Comments:a 1 # In l i n e comments# Comment i n a l i n e t o i t s e l f .a " # T h i s i s n o t a comment ! "Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousBasic conceptsNo lexical scopingScope determined by indentationf o r i i n range ( 1 0 ) :print " i n s i d e loop : " ,# Do something i n t h e l o o p .print i , i ip r i n t " l o o p i s done ! " # T h i s i s o u t s i d e t h e l o o p !Assignment to an object is by referenceEssentially, names are bound to objectsPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousOutline1IntroductionIntroduction to Python2Python TutorialPreliminariesData typesControl flow, functionsModules, exceptions, classesMiscellaneous3Numerics & PlottingNumPy ArraysPlotting: MatplotlibSciPy4Standard libraryQuick TourPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousBasic typesBasic objects: numbers (float, int, long, complex), strings,tuples, lists, dictionaries, functions, classes, types etc.Types are of two kinds: mutable and immutableImmutable types: numbers, strings, None and tuplesImmutables cannot be changed “in-place”Mutable types: lists, dictionaries, instances, etc.Mutable objects can be “changed”Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousWhat is an object?A loose and informal but handy descriptionAn object is a particular instance of a general class of thingsReal world exampleConsider the class of cars made by HondaA Honda Accord on the road, is a particular instance of thegeneral class of carsIt is an object in the general sense of the termPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousObjects in a programming languageThe object in the computer follows a similar ideaAn object has attributes and behaviorObject contains or manages data (attributes) and hasmethods (behavior)Together this lets one create representation of “real” things onthe computerProgrammers then create objects and manipulate themthrough their methods to get things doneIn Python everything is essentially an object – you don’t haveto worry about itPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousNumbers a 1 # I n t . l 1000000L # Long e 1.01325 e5 # f l o a t f 3.14159 # f l o a t c 1 1 j # Complex ! p r i n t f c / a(3.14159 3.14159 j ) p r i n t c . r e a l , c . imag1.0 1.0 abs ( c )1.4142135623730951Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousBoolean t fFalse fTrue fFalse True not tor tand tPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousStringss ’ this is a string ’s ’ T h i s one has " quotes " i n s i d e ! ’s " The r e v e r s e w i t h ’ s i n g l e quotes ’ i n s i d e ! "l "A l o n g s t r i n g spanning s e v e r a l l i n e s \one more l i n e \yet another "t " " "A t r i p l e quoted s t r i n gdoes n o t need t o be escaped a t t h e end and" can have nested quotes " and whatnot . " " "Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousStrings word " h e l l o " 2 word " w o r l d " # A r i t h m e t i c on s t r i n g sh e l l o h e l l o world p r i n t word [ 0 ] word [ 2 ] word [ 1]hlo # S t r i n g s are " immutable ". . . word [ 0 ] ’H ’Traceback ( most r e c e n t c a l l l a s t ) :F i l e " stdin " , l i n e 1 , in ?TypeError : o b j e c t doesn ’ t s u p p o r t i t e m assignment l e n ( word ) # The l e n g t h o f t h e s t r i n g5 s u ’ Unicode s t r i n g s ! ’ # unicode s t r i n gPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousMore on strings a ’ h e l l o w o r l d ’ a . s t a r t s w i t h ( ’ h e l l ’ )True a . endswith ( ’ l d ’ )True a . upper ( )’HELLO WORLD ’ a . upper ( ) . l o w e r ( )’ h e l l o world ’ a . s p l i t ( )[ ’ h e l l o ’ , ’ world ’ ] ’ ’ . j o i n ( [ ’ a ’ , ’ b ’ , ’ c ’ ] )’ abc ’ x , y 1 , 1.234 ’ x i s %s , y i s %s ’ %(x , y )’ x i s 1 , y i s 1.234 ’ # c o u l d a l s o do : ’ x i s %d , y i s %f ’%( x , y )See abhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousListsLists are mutableItems are indexed at 0Last element is -1Length: len(list)Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousList: examples a [ ’ spam ’ , ’ eggs ’ , 100 , 1234] a [ 0 ]’ spam ’ a [ 3 ]1234 a [ 2]100 a [ 1 : 1 ][ ’ eggs ’ , 100] a [ : 2 ] [ ’ bacon ’ , 2 2][ ’ spam ’ , ’ eggs ’ , ’ bacon ’ , 4 ] 2 a [ : 3 ] [ ’ Boe ! ’ ][ ’ spam ’ , ’ eggs ’ , 100 , ’ spam ’ , ’ eggs ’ , 100 , ’ Boe ! ’ ]Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousLists are mutable a [ ’ spam ’ , ’ eggs ’ , 100 , 1234] a [ 2 ] a [ 2 ] 23 a[ ’ spam ’ , ’ eggs ’ , 123 , 1234] a [ ’ spam ’ , ’ eggs ’ , 100 , 1234] a [ 0 : 2 ] [ 1 , 1 2 ] # Replace some i t e m s a[ 1 , 12 , 123 , 1234] a [ 0 : 2 ] [ ] # Remove some i t e m s a[ 1 2 3 , 1234]Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousList methods a [ ’ spam ’ , ’ eggs ’ , 100 , 1234] l e n ( a )4 a . r e v e r s e ( ) a[ 1 2 3 4 , 100 , ’ eggs ’ , ’ spam ’ ] a . append ( [ ’ x ’ , 1 ] ) # L i s t s can c o n t a i n l i s t s . a[ 1 2 3 4 , 100 , ’ eggs ’ , ’ spam ’ , [ ’ x ’ , 1 ] ] a . extend ( [ 1 , 2 ] ) # Extend t h e l i s t . a[ 1 2 3 4 , 100 , ’ eggs ’ , ’ spam ’ , [ ’ x ’ , 1 ] , 1 , 2 ]Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousTuples t ( 0 , 1 , 2 ) p r i n t t [ 0 ] , t [ 1 ] , t [ 2 ] , t [ 1 ] , t [ 2 ] , t [ 3]0 1 2 2 1 0 # Tuples are immutable !. . . t [0] 1Traceback ( most r e c e n t c a l l l a s t ) :F i l e " stdin " , l i n e 1 , in ?TypeError : o b j e c t doesn ’ t s u p p o r t i t e m assignmentPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousDictionariesAssociative arrays/mappingsIndexed by “keys” (keys must be immutable)dict[key] valuekeys() returns all keys of the dictvalues() returns the values of the dicthas key(key) returns if key is in the dictPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousDictionaries: example t e l { ’ j a c k ’ : 4098 , ’ sape ’ : 4139} t e l [ ’ guido ’ ] 4127 t e l{ ’ sape ’ : 4139 , ’ guido ’ : 4127 , ’ j a c k ’ : 4098} t e l [ ’ j a c k ’ ]4098 del t e l [ ’ sape ’ ] t e l [ ’ i r v ’ ] 4127 t e l{ ’ guido ’ : 4127 , ’ i r v ’ : 4127 , ’ j a c k ’ : 4098} t e l . keys ( )[ ’ guido ’ , ’ i r v ’ , ’ j a c k ’ ] t e l . has key ( ’ guido ’ )TruePrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousOutline1IntroductionIntroduction to Python2Python TutorialPreliminariesData typesControl flow, functionsModules, exceptions, classesMiscellaneous3Numerics & PlottingNumPy ArraysPlotting: MatplotlibSciPy4Standard libraryQuick TourPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousControl flowControl flow is primarily achieved using the following:if/elif/elseforwhilebreak, continue, else may be used to further controlpass can be used when syntactically necessary but nothingneeds to be donePrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousIf examplex i n t ( r a w i n p u t ( " Please e n t e r an i n t e g e r : " ) )# r a w i n p u t asks t h e user f o r i n p u t .# i n t ( ) t y p e c a s t s t h e r e s u l t i n g s t r i n g i n t o an i n t .i f x 0:x 0p r i n t ’ Negative changed t o zero ’e l i f x 0 :p r i n t ’ Zero ’e l i f x 1 :print ’ Single ’else :p r i n t ’ More ’Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousIf example a [ ’ c a t ’ , ’ window ’ , ’ d e f e n e s t r a t e ’ ] i f ’ c a t ’ i n a :.p r i n t "meaw".meaw p e t s { ’ c a t ’ : 1 , ’ dog ’ : 2 , ’ c r o c ’ : 10} i f ’ c r o c ’ i n p e t s :.print pets [ ’ croc ’ ].10Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes Miscellaneousfor example a [ ’ c a t ’ , ’ window ’ , ’ d e f e n e s t r a t e ’ ] f o r x i n a :print x , len ( x ).cat 3window 6d e f e n e s t r a t e 12 k n i g h t s { ’ g a l l a h a d ’ : ’ t h e pure ’ ,. . . ’ r o b i n ’ : ’ t h e brave ’ } f o r k , v i n k n i g h t s . i t e r i t e m s ( ) :.print k , v.g a l l a h a d t h e purer o b i n t h e bravePrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes Miscellaneousfor and range example f o r.0 01 12 43 94 16 a f o r.0 ’a ’1 ’b ’2 ’c ’i i n range ( 5 ) :print i , i i[ ’a ’ , ’b ’ , ’c ’ ]i , x i n enumerate ( a ) :print i , xPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes Miscellaneouswhile example . .112358# Fibonacci series :# t h e sum o f two elements d e f i n e s t h e n e x ta, b 0, 1while b 1 0 :print ba , b b , a bPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousFunctionsSupport default and keyword argumentsScope of variables in the function is localMutable items are passed by referenceFirst line after definition may be a documentation string(recommended!)Function definition and execution defines a name bound to thefunctionYou can assign a variable to a function!Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousFunctions: examples . .1 1 1 1def f i b ( n ) : # w r i t e F i b o n a c c i s e r i e s up t o n" " " P r i n t a F i b o n a c c i s e r i e s up t o n . " " "a, b 0, 1while b n :print b ,a , b b , a b# Now c a l l t h e f u n c t i o n we j u s t d e f i n e d :f i b (2000)2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597f f i b # Assign a v a r i a b l e t o a f u n c t i o nf (10)2 3 5 8Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousFunctions: default argumentsdef ask ok ( prompt , r e t r i e s 4 , c o m p l a i n t ’ Yes o r no ! ’ ) :while True :ok r a w i n p u t ( prompt )i f ok i n ( ’ y ’ , ’ ye ’ , ’ yes ’ ) :r e t u r n Truei f ok i n ( ’ n ’ , ’ no ’ , ’ nop ’ , ’ nope ’ ) :r e t u r n Falseretries retries 1i f r e t r i e s 0:r a i s e I O E r r o r , ’ bad user ’print complaintPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousFunctions: keyword argumentsdef p a r r o t ( v o l t a g e , s t a t e ’ a s t i f f ’ ,a c t i o n ’ voom ’ , t y p e ’ Norwegian Blue ’ ) :p r i n t " T h i s p a r r o t wouldn ’ t " , a c t i o n ,p r i n t " i f you p u t " , v o l t a g e , " V o l t s t h r o u g h i t . "p r i n t " L o v e l y plumage , t h e " , t y p ep r i n t " I t ’ s " , s t a t e , " ! "p a r r o t (1000)p a r r o t ( a c t i o n ’VOOOOOM ’ , v o l t a g e 1000000)p a r r o t ( ’ a thousand ’ , s t a t e ’ pushing up t h e d a i s i e s ’ )p a r r o t ( ’ a m i l l i o n ’ , ’ b e r e f t o f l i f e ’ , ’ jump ’ )Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousOutline1IntroductionIntroduction to Python2Python TutorialPreliminariesData typesControl flow, functionsModules, exceptions, classesMiscellaneous3Numerics & PlottingNumPy ArraysPlotting: MatplotlibSciPy4Standard libraryQuick TourPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousModulesDefine variables, functions and classes in a file with a .pyextensionThis file becomes a module!Modules are searched in the following:Current directoryStandard: /usr/lib/python2.3/site-packages/ etc.Directories specified in PYTHONPATHsys.path: current path settings (from the sys module)The import keyword “loads” a moduleOne can also use:from module import name1, name2, name2where name1 etc. are names in the module, “module”from module import * — imports everything frommodule, use only in interactive modePrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousModules: example# f o o . py some var 1def f i b ( n ) : # w r i t e F i b o n a c c i s e r i e s up t o n" " " P r i n t a F i b o n a c c i s e r i e s up t o n . " " "a, b 0, 1while b n :print b ,a , b b , a b# EOF 1 1 1import f o ofoo . f i b (10)2 3 5 8f o o . some varPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousNamespacesA mapping from names to objectsModules introduce a namespaceSo do classesThe running script’s namespace is mainA modules namespace is identified by its nameThe standard functions (like len) are in the builtinnamespaceNamespaces help organize different names and their bindingsto different objectsPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousExceptionsPython’s way of notifying you of errorsSeveral standard exceptions: SyntaxError, IOError etc.Users can also raise errorsUsers can create their own exceptionsExceptions can be “caught” via try/except blocksPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousException: examples 10 ( 1 / 0 )Traceback ( most r e c e n t c a l l l a s t ) :F i l e " stdin " , l i n e 1 , in ?Z e r o D i v i s i o n E r r o r : i n t e g e r d i v i s i o n or modulo by zero 4 spam 3Traceback ( most r e c e n t c a l l l a s t ) :F i l e " stdin " , l i n e 1 , in ?NameError : name ’ spam ’ i s not d e f i n e d ’ 2 ’ 2Traceback ( most r e c e n t c a l l l a s t ) :F i l e " stdin " , l i n e 1 , in ?TypeError : cannot concatenate ’ s t r ’ and ’ i n t ’ o b j e c t sPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousException: examples while True :.try :.x i n t ( r a w i n p u t ( " E n t e r a number : " ) ).break.except V a l u e E r r o r :.p r i n t " I n v a l i d number , t r y again . . . ". # To r a i s e e x c e p t i o n s. . . r a i s e V a l u e E r r o r , " your e r r o r message "Traceback ( most r e c e n t c a l l l a s t ) :F i l e " stdin " , l i n e 2 , in ?V a l u e E r r o r : your e r r o r messagePrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousClassesClass definitions when executed create class objectsClasses have attributes and may be instantiatedInstantiating the class object creates an instance of the classAll attributes are accessed via the value.attributesyntaxBoth class and instance attributes are supportedMethods represent the behavior of an object: crudely think ofthem as functions “belonging” to the objectAll methods in Python are “virtual”Classes may be subclassed (heh!)Multiple inheritance is supportedThere are no special public and private attributesPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousClasses: examplesclass MyClass ( o b j e c t ) :" Example c l a s s ( t h i s i s t h e c l a s s d o c s t r i n g ) "i 12345 # A c l a s s a t t r i b u t edef f ( s e l f ) :" T h i s i s t h e method d o c s t r i n g "return ’ h e l l o world ’ a MyClass ( ) # c r e a t e s an i n s t a n c e a . f ( )’ h e l l o world ’ # a . f ( ) i s e q u i v a l e n t t o MyClass . f ( a ). . . # T h i s a l s o e x p l a i n s why f has a ’ s e l f ’ argument . . . MyClass . f ( a )’ h e l l o world ’Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousClasses (continued)self is conventionally the first argument for a methodIn previous example, a.f is a method objectWhen a.f is called, it is passed the instance a as the firstargumentIf a method called init exists, it is called when theobject is createdIf a method called del exists, it is called before theobject is garbage collectedInstance attributes are set by simply “setting” them in selfOther special methods (by convention) like add let youdefine numeric types: u RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousClasses: examplesclass Bag ( MyClass ) : # Shows how t o d e r i v e c l a s s e sdef i n i t ( s e l f ) : # c a l l e d on o b j e c t c r e a t i o n .s e l f . data [ ] # an i n s t a n c e a t t r i b u t edef add ( s e l f , x ) :s e l f . data . append ( x )def addtwice ( s e l f , x ) :s e l f . add ( x )s e l f . add ( x ) a Bag ( ) a . f ( ) # I n h e r i t e d method’ h e l l o world ’ a . add ( 1 ) a . addtwice ( 2 ) a . data[1 , 2 , 2]Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousStand-alone scriptsConsider a file f.py:# ! / u s r / b i n / env python" " " Module l e v e l documentation . " " "# F i r s t l i n e t e l l s t h e s h e l l t h a t i t should use Python# t o i n t e r p r e t t h e code i n t h e f i l e .def f ( ) :print " f "# Check i f we are r u n n i n g s t a n d a l o n e o r as module .# When imported , name w i l l n o t be ’ main ’i f name ’ main ’ :# T h i s i s n o t executed when f . py i s i m p o r t e d .f ()Prabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousOutline1IntroductionIntroduction to Python2Python TutorialPreliminariesData typesControl flow, functionsModules, exceptions, classesMiscellaneous3Numerics & PlottingNumPy ArraysPlotting: MatplotlibSciPy4Standard libraryQuick TourPrabhu RamachandranIntroduction to Python

Introduction Python Tutorial Numerics & Plotting Standard libraryPreliminaries Data types Control flow, functions Modules, exceptions, classes MiscellaneousFile handling . . . # Reading f i l e s :f open ( ’ / path / t o / f i l e n a m e ’ )data f . read ( ) # Read e n t i r e f i l e .l i n e f . r e a d l i n e ( ) # Read one l i n e .# Read e n t i r e f i l e appending each l i n e i n t o a l i s tlines f . readlines ( )f . close ( ) # close the f i l e .# Writing f i l e s :f open ( ’ / path / t o / f i l e n a m e ’ , ’w ’ )f . w r i t e ( ’ h e l l o world

Introduction Python Tutorial Numerics & Plotting Standard library Introduction to Python Introduction Creator and BDFL: Guido van Rossum BDFL Benevolent Dictator For Life Conceived in December 1989 The name “Python”: Monty Python’s Flying Circus Current stable version of Python