Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Prabhu Ramachandran
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
Introduction
Resources
Why Python?
A quote
Use cases
Before we begin
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
Python is interpreted
Interpreted vs. Compiled
Interpreted languages allow for rapid testing/prototyping
Dynamically typed
Full introspection of code at runtime
Did I say dynamic?
Does not force OO or a particular programming paradigm
down your throat!
Preliminaries: IPython
Preliminaries . . .
Basic concepts
Dynamically typed
Assignments need not specify a type
a = 1
a = 1.1
a = " foo "
a = 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 ! "
Basic concepts
No lexical scoping
Scope determined by indentation
f 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 ∗ i
p 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 !
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
Basic types
What is an object?
Numbers
>>> 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 . imag
1.0 1.0
>>> abs ( c )
1.4142135623730951
Boolean
>>> t = True
>>> f = not t
False
>>> f or t
True
>>> f and t
False
Strings
s = ’ 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 g
does n o t need t o be escaped a t t h e end and
" can have nested quotes " and whatnot . " " "
Strings
More 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 http://docs.python.org/lib/typesseq-strings.html
Lists
List: examples
List methods
Tuples
>>> 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] = 1
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
Dictionaries
Associative arrays/mappings
Indexed by “keys” (keys must be immutable)
dict[key] = value
keys() returns all keys of the dict
values() returns the values of the dict
has_key(key) returns if key is in the dict
Dictionaries: example
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
Control flow
If example
If 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 ’ ]
...
10
for 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 3
window 6
d 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 pure
r o b i n t h e brave
while example
Functions
Functions: examples
>>> def 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, 1
... while 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)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>> f = f i b # Assign a v a r i a b l e t o a f u n c t i o n
>>> f (10)
1 1 2 3 5 8
def 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 e
p 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 ’ )
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
Modules
Modules: example
# −−− f o o . py −−−
some_var = 1
def 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, 1
while b < n :
print b ,
a , b = b , a+b
# EOF
>>> import f o o
>>> foo . f i b (10)
1 1 2 3 5 8
>>> f o o . some_var
1
Prabhu Ramachandran Introduction to Python
Introduction Python Tutorial Numerics & Plotting Standard library
Preliminaries Data types Control flow, functions Modules, exceptions, classes Miscellaneous
Namespaces
Exceptions
Exception: 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 ∗ 3
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 ?
NameError : name ’ spam ’ i s not d e f i n e d
>>> ’ 2 ’ + 2
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 : cannot concatenate ’ s t r ’ and ’ i n t ’ o b j e c t s
Exception: examples
Classes
Classes: examples
class 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 e
def 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 ’
Classes (continued)
Classes: examples
Stand-alone scripts
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
File 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 t
... lines = 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 \ n ’ )
Math
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
Basic concepts
Examples of numpy
Multi-dimensional arrays
>>> a = a r r a y ( [ [ 0 , 1 , 2 , 3 ] ,
... [10 ,11 ,12 ,13]])
>>> a . shape # ( rows , columns )
(2 , 4)
# Accessing and s e t t i n g v a l u e s
>>> a [ 1 , 3 ]
13
>>> a [ 1 , 3 ] = −1
>>> a [ 1 ] # The second row
array ([10 ,11 ,12 , −1])
# F l a t t e n / r a v e l a r r a y s t o 1D a r r a y s
>>> a . f l a t # o r r a v e l ( a )
array ([0 ,1 ,2 ,3 ,10 ,11 ,12 , −1])
# Note : f l a t r e f e r e n c e s o r i g i n a l memory
Prabhu Ramachandran Introduction to Python
Introduction Python Tutorial Numerics & Plotting Standard library
NumPy Arrays Plotting: Matplotlib SciPy
Slicing arrays
>>> a = a r r a y ( [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] )
>>> a [ 0 , 1 : 3 ]
array ( [ 2 , 3 ] )
>>> a [ 1 : , 1 : ]
array ( [ [ 5 , 6] ,
[8 , 9 ] ] )
>>> a [ : , 2 ]
array ( [ 3 , 6 , 9 ] )
# Striding . . .
>>> a [ 0 : : 2 , 0 : : 2 ]
array ( [ [ 1 , 3] ,
[7 , 9 ] ] )
# A l l these s l i c e s are r e f e r e n c e s t o t h e same memory !
array(object, dtype=None,
copy=1,order=None, subok=0,ndmin=0)
arange(start, stop=None, step=1,
dtype=None)
linspace(start, stop, num=50,
endpoint=True, retstep=False)
ones(shape, dtype=None, order=’C’)
zeros((d1,...,dn),dtype=float,order=’C’)
identity(n)
empty((d1,...,dn),dtype=float,order=’C’)
ones_like(x), zeros_like(x), empty_like(x)
Array math
Basic elementwise math (given two arrays a, b):
a + b → add(a, b)
a - b, → subtract(a, b)
a * b, → multiply(a, b)
a / b, → divide(a, b)
a % b, → remainder(a, b)
a ** b, → power(a, b)
Inplace operators: a += b, or add(a, b, a) etc.
Logical operations: equal (==), not_equal (!=),
less (<), greater (>) etc.
Trig and other functions: sin(x), arcsin(x),
sinh(x), exp(x), sqrt(x) etc.
sum(x, axis=0), product(x, axis=0): sum and
product of array elements
dot(a, b)
Prabhu Ramachandran Introduction to Python
Introduction Python Tutorial Numerics & Plotting Standard library
NumPy Arrays Plotting: Matplotlib SciPy
Advanced
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
About matplotlib
>>> x = arange ( 0 , 2 ∗ p i , 0 . 0 5 )
>>> p l o t ( x , s i n ( x ) ) # Same as p l o t ( x , s i n ( x ) , ’ b − ’)
>>> p l o t ( x , s i n ( x ) , ’ r o ’ )
>>> a x i s ( [ 0 , 2 ∗ p i , − 1 ,1])
>>> x l a b e l ( r ’ $ \ c h i $ ’ , c o l o r = ’ g ’ )
>>> y l a b e l ( r ’ s i n ( $ \ c h i $ ) ’ , c o l o r = ’ r ’ )
>>> t i t l e ( ’A s i m p l e f i g u r e ’ , f o n t s i z e =20)
>>> s a v e f i g ( ’ / tmp / t e s t . eps ’ )
# M u l t i p l e p l o t s i n one f i g u r e
>>> t = arange ( 0 . 0 , 5 . 2 , 0 . 2 )
# red dashes , b l u e squares and green t r i a n g l e s
>>> p l o t ( t , t , ’ r −− ’ , t , t ∗∗ 2 , ’ bs ’ , t , t ∗∗ 3 , ’ g^ ’ )
More on plotting
# Set p r o p e r t i e s o f o b j e c t s :
>>> p l o t ( x , s i n ( x ) , l i n e w i d t h = 2 . 0 , c o l o r = ’ r ’ )
>>> l , = p l o t ( x , s i n ( x ) )
>>> s e t p ( l , l i n e w i d t h = 2 . 0 , c o l o r = ’ r ’ )
>>> l . s e t _ l i n e w i d t h ( 2 . 0 ) ; l . s e t _ c o l o r ( ’ r ’ )
>>> draw ( ) # Redraws c u r r e n t f i g u r e .
>>> s e t p ( l ) # P r i n t s a v a i l a b l e p r o p e r t i e s
>>> c l o s e ( ) # Closes t h e f i g u r e .
# Multiple figures :
>>> f i g u r e ( 1 ) ; p l o t ( x , s i n ( x ) )
>>> f i g u r e ( 2 ) ; p l o t ( x , tanh ( x ) )
>>> f i g u r e ( 1 ) ; t i t l e ( ’ Easy as 1 ,2 ,3 ’ )
More on plotting . . .
More information
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
Using SciPy
Outline
1 Introduction
Introduction to Python
2 Python Tutorial
Preliminaries
Data types
Control flow, functions
Modules, exceptions, classes
Miscellaneous
3 Numerics & Plotting
NumPy Arrays
Plotting: Matplotlib
SciPy
4 Standard library
Quick Tour
Standard library
Very powerful
“Batteries included”
Example standard modules taken from the tutorial
Operating system interface: os
System, Command line arguments: sys
Regular expressions: re
Math: math, random
Internet access: urllib2, smtplib
Data compression: zlib, gzip, bz2, zipfile, and
tarfile
Unit testing: doctest and unittest
And a whole lot more!
Check out the Python Library reference:
http://docs.python.org/lib/lib.html
Stdlib: examples
>>> import os
>>> os . system ( ’ date ’ )
F r i Jun 10 2 2 : 1 3 : 0 9 IST 2005
0
>>> os . getcwd ( )
’ / home / prabhu ’
>>> os . c h d i r ( ’ / tmp ’ )
>>> import os
>>> d i r ( os )
< r e t u r n s a l i s t o f a l l module f u n c t i o n s >
>>> h e l p ( os )
< e x t e n s i v e manual page from module ’ s d o c s t r i n g s >
Stdlib: examples
Stdlib: examples
Stdlib: examples
>>> import u r l l i b 2
>>> f = u r l l i b 2 . u r l o p e n ( ’ h t t p : / / www. python . org / ’ )
>>> p r i n t f . read ( 1 0 0 )
<!DOCTYPE h t m l PUBLIC " − //W3C / / DTD HTML 4.01 T r a n s i t i o
<?xml− s t y l e s h e e t h r e f = " . / css / h t 2 h t m l
Stdlib: examples
>>> import z l i b
>>> s = ’ w i t c h which has which w i t c h e s w r i s t watch ’
>>> l e n ( s )
41
>>> t = z l i b . compress ( s )
>>> l e n ( t )
37
>>> z l i b . decompress ( t )
’ w i t c h which has which w i t c h e s w r i s t watch ’
>>> z l i b . crc32 ( t )
−1438085031
Summary
Introduced Python
Basic syntax
Basic types and data structures
Control flow
Functions
Modules
Exceptions
Classes
Standard library