Computational Science and Engineering in
Python
Hans Fangohr
Engineering and the Environment University of Southampton
United Kingdom
September 7, 2015
Outline I
1 Python prompt 2 Functions 3 About Python 4 Coding style 5 Conditionals, if-else 6 Sequences 7 Loops8 Some things revisited
9 File IO
10 Exceptions
11 Printing
12 Higher Order Functions
13 Modules 14 Default arguments 15 Namespaces 16 Python IDEs 17 List comprehension 18 Dictionaries
Outline II
19 Recursion
20 Common Computational Tasks
21 Root finding
22 Derivatives
23 Numpy
24 Higher Order Functions 2: Functional tools
25 Object Orientation and all that
26 Numerical Integration
27 Numpy usage examples
28 Scientific Python
29 ODEs
30 Sympy
31 Testing
32 Object Oriented Programming
First steps with the Python
prompt
The Python prompt
Spyder (or IDLE, or
python
or
python.exe
from
shell/Terminal/MS-Dos prompt, or
IPython
)
Python prompt waits for input:
> > >
Interactive Python prompt waits for input:
In [ 1 ] :Hello World program
Standard greeting:
p r i n t( " H e l l o W o r l d ! " )
Entered interactively in Python prompt:
> > > p r i n t( " H e l l o W o r l d ! " )H e l l o W o r l d !
Or in IPython prompt:
In [ 1 ] : p r i n t( " H e l l o w o r l d " ) H e l l o w o r l d
A calculator
> > > 2 + 3 5 > > > 42 - 1 5 . 3 2 6 . 7 > > > 100 * 11 1 1 0 0 > > > 2 4 0 0 / 20 120 > > > 2 ** 3 # 2 to the p o w e r of 3 8 > > > 9 ** 0.5 # s q r t of 9 3.0Create variables through assignment
> > > a = 10 > > > b = 20 > > > a 10 > > > b 20 > > > a + b 30 > > > ab2 = ( a + b ) / 2 > > > ab2 15Important data types / type()
> > > a = 1 > > > t y p e( a ) <t y p e ’ int ’ > # i n t e g e r > > > b = 1.0 > > > t y p e( b ) <t y p e ’ f l o a t ’ > # f l o a t > > > c = ’ 1.0 ’ > > > t y p e( c ) <t y p e ’ str ’ > # s t r i n g > > > d = 1 + 3 j > > > t y p e( d ) <t y p e ’ c o m p l e x ’ > # c o m p l e x n u m b e rBeware of integer division
This is the problem:
> > > 1 / 20 # e x p e c t e d 0.5 , not 0
Solution: change (at least) one of the integer numbers into a
floating point number (i.e.
1
→
1.0
).
> > > 1.0 / 2 0.5
> > > 1 / 2.0 0.5
Summary useful commands (introspection)
print(x)
to display the object
x
type(x)
to determine the type of object
x
help(x)
to obtain the documentation string
dir(x)
to display the methods and members of object
x
,
or the current name space (
dir()
).
Example:
> > > h e l p ( " abs " ) H e l p on built - in f u n c t i o n abs : abs ( . . . ) abs ( n u m b e r ) - > n u m b e r R e t u r n the a b s o l u t e v a l u e of the a r g u m e n t .Interactive documentation, introspection
> > > w o r d = ’ t e s t ’ > > > p r i n t ( w o r d ) t e s t > > > t y p e ( w o r d ) < t y p e ’ str ’ > > > > dir ( w o r d ) [ ’ _ _ a d d _ _ ’ , ’ _ _ c l a s s _ _ ’ , ’ _ _ c o n t a i n s _ _ ’ , ... , ’ _ _ d o c _ _ ’ , ... , ’ c a p i t a l i z e ’ , < snip > , ’ e n d s w i t h ’ , ... , ’ u p p e r ’ , ’ z f i l l ’ ] > > > w o r d . u p p e r () ’ T E S T ’ > > > w o r d . c a p i t a l i z e () ’ T e s t ’ > > > w o r d . e n d s w i t h ( ’ st ’ ) T r u e > > > w o r d . e n d s w i t h ( ’ a ’ ) F a l s eFirst use of functions
Example 1:
def m y s u m ( a , b ): r e t u r n a + b
# m a i n p r o g r a m s t a r t s h e r e
Functions should be documented
def m y s u m ( a , b ):
""" R e t u r n the sum of p a r a m e t e r s a and b . H a n s Fangohr , f a n g o h r @ s o t o n . ac . uk ,
l a s t m o d i f i e d 2 4 / 0 9 / 2 0 1 3 """
r e t u r n a + b
# m a i n p r o g r a m s t a r t s h e r e
p r i n t " The sum of 3 and 4 is " , m y s u m (3 , 4)
Can now use the help function for our new function:
> > > h e l p( m y s u m )H e l p on f u n c t i o n m y s u m in m o d u l e _ _ m a i n _ _ :
m y s u m ( a , b )
R e t u r n the sum of p a r a m e t e r s a and b . H a n s Fangohr , f a n g o h r @ s o t o n . ac . uk , l a s t m o d i f i e d 2 4 / 0 9 / 2 0 1 3
Function terminology
x = -1.5 y = abs( x )
x
is the
argument
given to the function
y
is the
return value
(the result of the function’s
computation)
Functions may expect zero, one or more arguments
Not all functions (seem to) return a value. (If no
return
Function example
def p l u s 4 2 ( n ): """ Add 42 to n and r e t u r n """ # d o c s t r i n g l = n + 42 # b o d y of # f u n c t i o n r e t u r n l a = 8 b = p l u s 4 2 ( a ) # not p a r t of f u n c t i o n d e f i n i t i o nSummary functions
Functions provide (black boxes of) functionality: crucial
building blocks that hide complexity
interaction (input, output) through input arguments and
return values (
printing
and
returning
values is not the
same!)
docstring provides the specification (contract) of the
function’s input, output and behaviour
a function should (normally) not modify input arguments
(watch out for lists, dicts, more complex data structures
as input arguments)
Functions printing vs returning values I
Given the following two function definitions:
def p r i n t 4 2 ():p r i n t( 4 2 )
def r e t u r n 4 2 (): r e t u r n 42
we use the Python prompt to explore the difference:
> > > b = r e t u r n 4 2 () # r e t u r n 42 , is a s s i g n e d > > > p r i n t( b ) # to b 42 > > > a = p r i n t 4 2 () # r e t u r n None , and 42 # p r i n t 42 to s c r e e n > > > p r i n t( a ) N o n e # s p e c i a l o b j e c t N o n eFunctions printing vs returning values II
If we use IPython, it shows whether a function returns
something (i.e. not None) through the
Out [ ]
token:
In [ 1 ] : r e t u r n 4 2 ()Out [ 1 ] : 42 # R e t u r n v a l u e of 42
In [ 2 ] : p r i n t 4 2 ()
42 # No ’ Out [ ] ’ , so no
Python
What is Python?
High level programming language
interpreted
Quite similar to MATLAB
supports three main programming styles
(imperative=procedural, object-oriented, functional)
General purpose tool, yet good for numeric work with
extension libraries
Availability
Python is free
Python is platform independent (works on Windows,
Linux/Unix, Mac OS, . . . )
Python documentation
There is lots of documentation that you should learn to use:
Teaching materials on website, including these slides and
a text-book like documents
Online documentation, for example
Python home page (http://www.python.org) Pylab/Matplotlib (plotting as in Matlab)
Numpy (fast vectors and matrices, (NUMerical PYthon) SciPy (scientific algorithms,odeint)
Visual Python (3d visualisation) SymPy (Symbolic calculation)
interactive documentation
Which Python version
There are currently two versions of Python:
Python 2.x and
Python 3.x
We will use version 2.7 (some 3rd party packages need
it), but use Python 3 syntax where allowed
Python 2.x and 3.x are incompatible although the
changes only affect very few commands.
Write new programs in Python 3 where possible.
See webpages for notes on installation of Python on
computers.
The math module (
import math
)
> > > i m p o r t m a t h > > > m a t h . s q r t (4) 2.0 > > > m a t h . pi 3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 > > > dir( m a t h ) # a t t r i b u t e s of ’ m a t h ’ o b j e c t [ ’ _ _ d o c _ _ ’ , ’ _ _ f i l e _ _ ’ , < s n i p > ’ a c o s ’ , ’ a c o s h ’ , ’ a s i n ’ , ’ a s i n h ’ , ’ a t a n ’ , ’ a t a n 2 ’ , ’ a t a n h ’ , ’ c e i l ’ , ’ c o p y s i g n ’ , ’ cos ’ , ’ e ’ , ’ erf ’ , ’ exp ’ , < snip > , ’ s q r t ’ , ’ tan ’ , ’ t a n h ’ , ’ t r u n c ’ ]> > > h e l p( m a t h . s q r t ) # ask for h e l p on s q r t
s q r t ( . . . ) s q r t ( x )
Name spaces and modules
Three (good) options to access a module:
1
use the full name:
i m p o r t m a t h
p r i n t m a t h . sin ( 0 . 5 )
2
use some abbreviation
i m p o r t m a t h as m p r i n t m . sin ( 0 . 5 ) p r i n t m . pi
3
import all objects we need explicitly
f r o m m a t h i m p o r t sin , pi p r i n t sin ( 0 . 5 )
Integer division (revisited) I
Reminder
> > > 1 / 20 # e x p e c t e d 0.5 , not 0
Solutions:
change (at least) one of the integer numbers into a
floating point number (i.e.
1
→
1.0
).
> > > 1.0 / 2 0.5
Or use
float
function to convert variable to float
> > > a = 1> > > b = 2
> > > 1 / f l o a t( b ) 0.5
Integer division (revisited) II
Or make use of Python’s future division:
> > > f r o m _ _ f u t u r e _ _ i m p o r t d i v i s i o n > > > 1 / 20.5
If you really want integer division, use
//
:
Coding style
Python programs
must
follow Python syntax.
Python programs
should
follow Python style guide,
because
readability is key (debugging, documentation, team
effort)
Common style guide: PEP8
See
http://www.python.org/dev/peps/pep-0008/
This document gives coding conventions for the Python code comprising the standard library in the main Python distribution. This style guide evolves over time as additional conventions are identified and past conventions are rendered obsolete by changes in the language itself.
Many projects have their own coding style guidelines. In the event of any conflicts, such project-specific guides take precedence for that project.
One of Guido’s key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. ”Readability counts”.
When not to follow this style guide:
When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.
To be consistent with surrounding code that also breaks it (maybe for historic reasons) – although this is also an opportunity to clean up someone else’s mess (in true XP style).
PEP8 Style guide
Indentation: use 4 spaces
One space around
=
operator:
c = 5
and not
c=5
.
Spaces around arithmetic operators can vary:
x = 3*a +
4*b
is okay, but also okay to write
x = 3 * a + 4 * b
.
No space before and after parentheses:
x = sin(x)
but
not
x = sin( x )
A space after comma:
range(5, 10)
and not
range(5,10)
.
No whitespace at end of line
No whitespace in empty line
One or no empty line between statements within function
Two empty lines between functions
One import statement per line
import first standand Python library, then third-party
packages (numpy, scipy, ...), then our own modules.
PEP8 Style Summary
Try to follow PEP8 guide, in particular for new code
Use tools to help us, for example Spyder editor can show
PEP8 violations
Truth values I
The python values
True
and
False
are special inbuilt objects:
> > > a = T r u e > > > p r i n t( a ) T r u e > > > t y p e( a ) <t y p e ’ b o o l ’ > > > > b = F a l s e > > > p r i n t( b ) F a l s e > > > t y p e( b ) <t y p e ’ b o o l ’ >We can operate with these two logical values using boolean
logic, for example the logical and operation (
and
):
Truth values II
> > > T r u e and T r u e # l o g i c a l and o p e r a t i o n T r u e > > > T r u e and F a l s e F a l s e > > > F a l s e and T r u e F a l s e > > > T r u e and T r u e T r u eThere is also logical or (
or
) and the negation (
not
):
> > > T r u e or F a l s e T r u e > > > not T r u e F a l s e > > > not F a l s e T r u e > > > T r u e and not F a l s e T r u eTruth values III
In computer code, we often need to evaluate some expression
that is either true or false (sometimes called a “predicate”).
For example:
> > > x = 30 # a s s i g n 30 to x > > > x >= 30 # is x g r e a t e r t h a n or e q u a l to 30? T r u e > > > x > 15 # is x g r e a t e r t h a n 15 T r u e > > > x > 30 F a l s e > > > x == 30 # is x the s a m e as 30? T r u e> > > not x == 42 # is x not the s a m e as 42?
T r u e
> > > x != 42 # is x not the s a m e as 42?
if-then-else I
The
if-else
command allows to branch the execution path
depending on a condition. For example:
> > > x = 30 # a s s i g n 30 to x > > > if x > 30: # p r e d i c a t e : is x > 30 ... p r i n t( " Yes " ) # if True , do t h i s ... e l s e: ... p r i n t( " No " ) # if False , do t h i s ... No
The general structure of the
if-else
statement is
if A :B e l s e: C
if-then-else II
If
A
evaluates to
True
, then all commands
B
are carried
out (and
C
is skipped).
If
A
evaluates to
False
, then all commands
C
are carried
out (and
B
) is skipped.
if
and
else
are Python keywords.
A
and
B
can each consist of multiple lines, and are grouped
through indentation as usual in Python.
if-else example
def s l e n g t h 1 ( s ): """ R e t u r n s a s t r i n g d e s c r i b i n g the l e n g t h of the s e q u e n c e s """ if len( s ) > 10: ans = ’ v e r y l o n g ’ e l s e: ans = ’ n o r m a l ’ r e t u r n ans > > > s l e n g t h 1 ( " H e l l o " ) ’ n o r m a l ’ > > > s l e n g t h 1 ( " H e l l o H e l l o " ) ’ n o r m a l ’ > > > s l e n g t h 1 ( " H e l l o a g a i n " ) ’ v e r y l o n g ’if-elif-else example I
If more cases need to be distinguished, we can use the
additional keyword
elif
(standing for ELse IF) as many times
as desired:
def s l e n g t h 2 ( s ): if len( s ) == 0: ans = ’ e m p t y ’ e l i f len( s ) > 10: ans = ’ v e r y l o n g ’ e l i f len( s ) > 7: ans = ’ n o r m a l ’ e l s e: ans = ’ s h o r t ’ r e t u r n ansif-elif-else example II
> > > s l e n g t h 2 ( " " ) ’ e m p t y ’ > > > s l e n g t h 2 ( " G o o d M o r n i n g " ) ’ v e r y l o n g ’ > > > s l e n g t h 2 ( " G r e e t i n g s " ) ’ n o r m a l ’ > > > s l e n g t h 2 ( " Hi " ) ’ s h o r t ’LAB2
Sequences overview
Different types of sequences
strings
lists (mutable)
tuples (immutable)
arrays (mutable, part of numpy)
They share common commands.
Strings
> > > a = " H e l l o W o r l d " > > > t y p e( a ) <t y p e ’ str ’ > > > > len( a ) 11 > > > p r i n t( a ) H e l l o W o r l dDifferent possibilities to limit strings
’ A s t r i n g ’ " A n o t h e r s t r i n g " " A s t r i n g w i t h a ’ in the m i d d l e " """ A s t r i n g w i t h t r i p l e q u o t e s can e x t e n d o v e r s e v e r a l l i n e s """Strings 2 (exercise)
Enter this line on the Python prompt:
>>> a="One"; b="Two"; c="Three"
Exercise: What do the following expressions evaluate to?
1
d = a + b + c
2
5 * d
3
d[0], d[1], d[2]
(indexing)
4
d[-1]
Strings 3 (exercise)
> > > s = """ My f i r s t l o o k at P y t h o n was an ... a c c i d e n t , and I d i d n ’ t m u c h l i k e w h a t ... I saw at the t i m e . """
count the number of (i) letters ’e’ and (ii) substrings ’an’
s
replace all letters ’a’ with ’0’
make all letters uppercase
make all capital letters lowercase, and all lower case
letters to capitals
Lists
[] # the e m p t y l i s t
[ 4 2 ] # a 1 - e l e m e n t l i s t
[5 , ’ h e l l o ’ , 1 7 . 3 ] # a 3 - e l e m e n t l i s t
[[1 , 2] , [3 , 4] , [5 , 6]] # a l i s t of l i s t s
Lists store an ordered sequence of Python objects
Access through index (and slicing) as for strings.
Important function:
range()
(
xrange
)
use
help()
, often used list methods is
append()
(In general computer science terminology, vector or array might be better name as the actual implementation is not a linked list, but directO(1)access through the index is possible.)
Example program: using lists
> > > a = [] # c r e a t e s a l i s t > > > a . a p p e n d ( ’ dog ’ ) # a p p e n d s s t r i n g ’ dog ’ > > > a . a p p e n d ( ’ cat ’ ) # ... > > > a . a p p e n d ( ’ m o u s e ’ ) > > > p r i n t( a ) [ ’ dog ’ , ’ cat ’ , ’ m o u s e ’ ] > > > p r i n t( a [ 0 ] ) # a c c e s s f i r s t e l e m e n t dog # ( w i t h i n d e x 0) > > > p r i n t( a [ 1 ] ) # ... cat > > > p r i n t( a [ 2 ] ) m o u s e > > > p r i n t( a [ -1]) # a c c e s s l a s t e l e m e n t m o u s e > > > p r i n t( a [ -2]) # s e c o n d l a s t catExample program: lists containing a list
> > > a =[ ’ dog ’ , ’ cat ’ , ’ m o u s e ’ , [1 , 10 , 100 , 1 0 0 0 ] ] > > > a [ ’ dog ’ , ’ cat ’ , ’ m o u s e ’ , [1 , 10 , 100 , 1 0 0 0 ] ] > > > a [0] dog > > > a [3] [1 , 10 , 100 , 1 0 0 0 ] > > > max( a [ 3 ] ) 1 0 0 0 > > > min( a [ 3 ] ) 1 > > > a [ 3 ] [ 0 ] 1 > > > a [ 3 ] [ 1 ] 10 > > > a [ 3 ] [ 3 ] 1 0 0 0Sequences – more examples
> > > a = " h e l l o w o r l d " > > > a [4] ’ o ’ > > > a [ 4 : 7 ] ’ o w ’ > > > len( a ) 11 > > > ’ d ’ in a T r u e > > > ’ x ’ in a F a l s e > > > a + a ’ h e l l o w o r l d h e l l o w o r l d ’ > > > 3 * a ’ h e l l o w o r l d h e l l o w o r l d h e l l o w o r l d ’Tuples I
tuples are very similar to lists
tuples are usually written using parentheses (↔
“round
brackets”):
> > > t = (3 , 4 , 50) > > > t (3 , 4 , 50) > > > t y p e( t ) <t y p e ’ t u p l e ’ > > > > l = [3 , 4 , 50] # c o m p a r e w i t h l i s t o b j e c t > > > l [3 , 4 , 50] > > > t y p e( l ) <t y p e ’ l i s t ’ >Tuples II
> > > t [1] 4
> > > t [: -1] (3 , 4)
tuples are defined by the comma (!)
> > > a = 10 , 20 , 30> > > t y p e( a ) <t y p e ’ t u p l e ’ >
the parentheses are usually optional (but should be
written anyway):
> > > a = (10 , 20 , 30) > > > t y p e( a )
Tuples III
So why do we need tuples (in addition to lists)?
1
use tuples if you want to make sure that a set of objects
doesn’t change.
2
allow to assign several variables in one line (known as
tuple packing
and
unpacking
)
x , y , z = 0 , 0 , 1This allows ’instantaneous swap’ of values:
a , b = b , a
3
functions return tuples if they return more than one object
def f ( x ):
r e t u r n x **2 , x **3
Tuples IV
4
tuples can be used as keys for dictionaries as they are
(Im)mutables
Strings — like tuples — are immutable:
> > > a = ’ h e l l o w o r l d ’ # S t r i n g e x a m p l e > > > a [4] = ’ x ’ T r a c e b a c k ( m o s t 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 ? T y p e E r r o r : o b j e c t d o e s n ’ t s u p p o r t i t e m a s s i g n m e n t
strings can only be ’changed’ by creating a new string, for
example:
> > > a = a [ 0 : 3 ] + ’ x ’ + a [ 4 : ] > > > a
Summary sequences
lists, strings and tuples (and arrays) are sequences. For
example
list
a = [1, 10, 42, 400]or
string
a = ’hello world’sequences share the following operations
a[i]
returns
i
-th element of
a
a[i:j]
returns elements
i
up to
j
−
1
len(a)
returns number of elements in sequence
min(a)
returns smallest value in sequence
max(a)
returns largest value in sequence
x in a
returns
True
if
x
is element in
a
a + b
concatenates
a
and
b
n * a
creates
n
copies of sequence
a
In the table above,
a
and
b
are sequences,
i
,
j
and
n
are
integers.
Example programmes: for-loops I
a n i m a l s = [ ’ dog ’ , ’ cat ’ , ’ m o u s e ’ ]
for a n i m a l in a n i m a l s :
p r i n t( " T h i s is the {} " .f o r m a t( a n i m a l ))
produces this output:
T h i s is the dog T h i s is the cat T h i s is the m o u s eThe
range(n)
command is used to create lists with increasing
Example programmes: for-loops II
> > > r a n g e(6) [0 , 1 , 2 , 3 , 4 , 5] > > > r a n g e(3) [0 , 1 , 2] for i in r a n g e( 6 ) : p r i n t( " the s q u a r e of {} is {} " .f o r m a t( i , i ** 2))produces this output:
the s q u a r e of 0 is 0 the s q u a r e of 1 is 1 the s q u a r e of 2 is 4 the s q u a r e of 3 is 9 the s q u a r e of 4 is 16 the s q u a r e of 5 is 25
Example programmes: for-loops III
The
range
function
range([start,] stop [,step])
returns a list of
integers from start to
but not including
stop. Example
> > > r a n g e(1 ,4)[1 , 2 , 3]
Iterating: for-loop
for
loop iterates over sequence
Examples:
for i in r a n g e( 5 ) : p r i n t( i )
for i in [0 , 3 , 4 , 1 9 ] : p r i n t( i )
for a n i m a l in [ ’ dog ’ , ’ cat ’ , ’ m o u s e ’ ]: p r i n t( a n i m a l )
for l e t t e r in " H e l l o W o r l d " : p r i n t( l e t t e r )
Branching: If-then-else
Example 1 (if-then-else)
a = 42 if a > 0: p r i n t( " a is p o s i t i v e " ) e l s e: p r i n t( " a is n e g a t i v e or z e r o " )Example 2 (if-then-elif-else)
a = 42 if a > 0: p r i n t( " a is p o s i t i v e " ) e l i f a == 0: p r i n t( " a is z e r o " ) e l s e: p r i n t( " a is n e g a t i v e " )Another iteration example
This example generates a sequence of numbers often used in
hotels to label floors (more info)
def s k i p 1 3 ( a , b ): r e s u l t = [] for k in r a n g e ( a , b ): if k == 13: p a s s # do n o t h i n g e l s e: r e s u l t . a p p e n d ( k ) r e t u r n r e s u l t
Exercise range double
Write a function
range double(n)
that behaves in the same
way as the in-built python function
range(n)
but which
returns twice the number for every entry. For example:
> > > r a n g e _ d o u b l e (4) [0 , 2 , 4 , 6]
> > > r a n g e _ d o u b l e ( 1 0 )
[0 , 2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18]
For comparison the behaviour of
range
:
> > > r a n g e(4) [0 , 1 , 2 , 3] > > > r a n g e( 1 0 )
[0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]
Exercise: First In First Out (FIFO) queue
Write a
First-In-First-Out
queue implementation, with
functions:
add(name)
to add a customer with name
name
(call this
when a new customer arrives)
next()
to be called when the next customer will be
served. This function returns the name of the customer
show()
to print all names of customers that are currently
waiting
length()
to return the number of currently waiting
customers
Suggest to use a global variable
q
and define this in the first
line of the file by assigning an empty list:
q = []
.
While loops
a
for
loop iterates over a given sequence
a
while
loop iterates while a condition is fulfilled
Example:
x =64 w h i l e x >1: x = x /2 p r i n t( x )produces
32 16 8 4 2 1While loop example 2
Determine
:
eps = 1.0 w h i l e eps + 1 > 1: eps = eps / 2.0 p r i n t( " e p s i l o n is {} " .f o r m a t( eps ))identical to
eps = 1.0 w h i l e T r u e : if eps + 1 == 1: b r e a k # l e a v e s i n n e r m o s t l o o p eps = eps / 2.0 p r i n t( " e p s i l o n is {} " .f o r m a t( eps ))Output:
e p s i l o n is 1 . 1 1 0 2 2 3 0 2 4 6 3 e -16What are variables?
In Python, variables are references to objects.
This is why in the following example,
a
and
b
represent the
same list:
a
and
b
are two
different references
to the
same
object
:
> > > a = [0 , 2 , 4 , 6] # b i n d n a m e ’ a ’ to l i s t > > > a # o b j e c t [0 ,2 ,4 ,6]. [0 , 2 , 4 , 6] > > > b = a # b i n d n a m e ’ b ’ to the s a m e > > > b # l i s t o b j e c t . [0 , 2 , 4 , 6] > > > b [1] # s h o w s e c o n d e l e m e n t in l i s t 2 # o b j e c t . > > > b [1] = 10 # m o d i f y 2 nd e l e m e m n t ( via b ). > > > b # s h o w b . [0 , 100 , 4 , 6] > > > a # s h o w a . [0 , 100 , 4 , 6]id
,
==
and
is
Two objects
a
and
b
are the
same object
if they live in
the same place in memory (
id()
). We check with
id(a)
== id(b)
or
a is b
.
Two different objects can have the
same value
. We check
with
==
See “Equality and identity“, section 3.5 > > > a = 1 > > > b = 1.0 > > > id( a ); id( b ) 4 2 9 8 1 8 7 6 2 4 # not in the s a m e p l a c e 4 2 9 8 1 9 7 7 1 2 # in m e m o r y > > > a is b # i . e . not the s a m e o b j e c t s F a l s e > > > a == b # but c a r r y the s a m e v a l u e T r u e > > > a = [1 , 2 , 3] > > > b = a # b is r e f e r e n c e to o b j e c t of a > > > a is b # t h u s t h e y are the s a m e T r u eFunctions - side effect
If we carry out some activity A, and this has an
(unexpected) effect on something else, we speak about
side effects
. Example:
def sum( xs ): s = 0 for i in r a n g e(len( xs )): s = s + xs . pop () r e t u r n s xs = [0 , 1 , 2 , 3] p r i n t( " xs = {} " .f o r m a t( xs )) p r i n t( " sum ( xs ) = { } " .f o r m a t(sum( xs ))) p r i n t( " xs = {} " .f o r m a t( xs )) p r i n t( " sum ( xs ) = { } " .f o r m a t(sum( xs )))Output:
xs = [0 , 1 , 2 , 3] sum( xs )= 6Functions - side effect 2
Better ways to compute the sum of a list
xs
(or sequence in
general)
use in-built command
sum(xs)
use indices to iterate over list
def sum( xs ):s =0
for i in r a n g e(len( xs )): s = s + xs [ i ]
r e t u r n s
or (better): iterate over list elements directly
def sum( xs ):s =0
for e l e m in xs s = s + e l e m r e t u r n s
To print or to return?
A function that returns the control flow through the
return
keyword, will return the object given after
return
.
A function that does not use the
return
keyword,
returns the special object
None
.
Generally, functions should return a value
Generally, functions should not print anything
Calling functions from the prompt can cause some
confusion here: if the function returns a value and the
value is not assigned, it will be printed.
File input/output
It is a (surprisingly) common task to
read some input data file
do some calculation/filtering/processing with the data
write some output data file with results
Writing a text file I
> > > f o u t = o p e n( ’ t e s t . txt ’ , ’ w ’ ) # W r i t e
> > > f o u t . w r i t e ( " f i r s t l i n e \ n s e c o n d l i n e " ) > > > f o u t . c l o s e ()
creates a file
test.txt
that reads
f i r s t l i n es e c o n d l i n e
To write data, we need to use the
’w’
mode:
f = o p e n( ’ m y d a t a f i l e . txt ’ , ’ w ’ )If the file exists, it will be overridden with an empty file
when the open command is executed.
The file object
f
has a method
f.write
which takes a
string as in input argument.
Reading a text file I
We create a file object f using
> > > f = o p e n( ’ t e s t . txt ’ , ’ r ’ ) # R e a d
and have different ways of reading the data:
Example 1 (
readlines()
)
f.readlines()
returns a list of strings (each being one
line)
> > > f = o p e n( ’ t e s t . txt ’ , ’ r ’ ) > > > l i n e s = f . r e a d l i n e s () > > > f . c l o s e () > > > l i n e s [ ’ f i r s t l i n e \ n ’ , ’ s e c o n d l i n e ’ ]Reading a text file II
Example 2 (
read()
)
f.read()
returns one long string for the whole file
> > > f = o p e n( ’ t e s t . txt ’ , ’ r ’ )> > > d a t a = f . r e a d () > > > f . c l o s e ()
> > > d a t a
’ f i r s t l i n e \ n s e c o n d l i n e ’
Advanced:
f
is also an iterable object (important for large
files)
> > > f = o p e n( ’ t e s t . txt ’ , ’ r ’ ) > > > for l i n e in f : ... p r i n t( l i n e ) , ... f i r s t l i n e s e c o n d l i n e > > > f . c l o s e ()Reading a text file III
Advanced: Could use a context:
> > > w i t h o p e n( ’ t e s t . txt ’ , ’ r ’ ) as f : ... d a t a = f . r e a d ()
... > > > d a t a
Reading a file, iterating over lines
Often we want to process line by line. Typical code
fragment:
f = o p e n( ’ m y f i l e . txt ’ , ’ r ’ ) l i n e s = f . r e a d l i n e s () f . c l o s e () # T h e n do s o m e p r o c e s s i n g w i t h the # l i n e s o b j e c tlines
is a list of strings, each representing one line of the
file.
Splitting a string
We often need to split a string into smaller parts: use
string method
split()
:
(try
help("".split)
at the Python prompt for more
info)
Example: Take a string and display each word on a separate
line:
> > > c = ’ T h i s is my s t r i n g ’ > > > c . s p l i t () [ ’ T h i s ’ , ’ is ’ , ’ my ’ , ’ s t r i n g ’ ] > > > c . s p l i t ( ’ i ’ ) [ ’ Th ’ , ’ s ’ , ’ s my str ’ , ’ ng ’ ]Exercise: Shopping list
Given a list
b r e a d 1 1 . 3 9 t o m a t o e s 6 0 . 2 6 m i l k 3 1 . 4 5 c o f f e e 3 2 . 9 9Write program that computes total cost per item, and writes
to
shopping cost.txt
:
b r e a d 1 . 3 9 t o m a t o e s 1 . 5 6 m i l k 4 . 3 5 c o f f e e 8 . 9 7
One solution
One solution is
shopping cost.py
fin = o p e n( ’ s h o p p i n g . txt ’ ) l i n e s = fin . r e a d l i n e s () fin . c l o s e () f o u t = o p e n( ’ s h o p p i n g _ c o s t . txt ’ , ’ w ’ ) for l i n e in l i n e s : w o r d s = l i n e . s p l i t () i t e m n a m e = w o r d s [0] n u m b e r = int( w o r d s [ 1 ] ) c o s t = f l o a t( w o r d s [ 2 ] ) t o t a l c o s t = n u m b e r * c o s t f o u t . w r i t e ( " { : 2 0 } {}\ n " .f o r m a t( i t e m n a m e , t o t a l c o s t )) f o u t . c l o s e ()
Exercise
Write function
print line sum of file(filename)
that
reads a file of name
filename
containing numbers separated
by spaces, and which computes and prints the sum for each
line. A data file might look like
1 2 4 67 -34 340
0 45 3 2
17
Exceptions
Errors arising during the execution of a program result in “exceptions”.
We have seen exceptions before, for example when dividing by zero:
> > > 4.5 / 0
T r a c e b a c k ( most r e c e n t call last ): File " < stdin > " , line 1 , in ? Z e r o D i v i s i o n E r r o r : f l o a t d i v i s i o n or when we try to access an undefined variable: > > > p r i n t ( x )
T r a c e b a c k ( most r e c e n t call last ): File " < stdin > " , line 1 , in ? N a m e E r r o r : name ’ x ’ is not d e f i n e d
Exceptions are a modern way of dealing with error situations We will now see how
what exceptions are coming with Python we can “catch” exceptions
In-built Python exceptions I
Python’s inbuilt exceptions can be found in the
exceptions
module.
Users can provide their own exception classes (by inheriting fromException).
> > > i m p o r t e x c e p t i o n s > > > h e l p( e x c e p t i o n s ) B a s e E x c e p t i o n E x c e p t i o n S t a n d a r d E r r o r A r i t h m e t i c E r r o r F l o a t i n g P o i n t E r r o r O v e r f l o w E r r o r Z e r o D i v i s i o n E r r o r A s s e r t i o n E r r o r A t t r i b u t e E r r o r B u f f e r E r r o r E O F E r r o r E n v i r o n m e n t E r r o r I O E r r o r O S E r r o r I m p o r t E r r o r L o o k u p E r r o r I n d e x E r r o r K e y E r r o r M e m o r y E r r o r N a m e E r r o r U n b o u n d L o c a l E r r o r R e f e r e n c e E r r o r
In-built Python exceptions II
R u n t i m e E r r o r N o t I m p l e m e n t e d E r r o r S y n t a x E r r o r I n d e n t a t i o n E r r o r T a b E r r o r S y s t e m E r r o r T y p e E r r o r V a l u e E r r o r U n i c o d e E r r o r U n i c o d e D e c o d e E r r o r U n i c o d e E n c o d e E r r o r U n i c o d e T r a n s l a t e E r r o r S t o p I t e r a t i o n W a r n i n g B y t e s W a r n i n g D e p r e c a t i o n W a r n i n g F u t u r e W a r n i n g I m p o r t W a r n i n g P e n d i n g D e p r e c a t i o n W a r n i n g R u n t i m e W a r n i n g S y n t a x W a r n i n g U n i c o d e W a r n i n g U s e r W a r n i n g G e n e r a t o r E x i t K e y b o a r d I n t e r r u p t S y s t e m E x i tCatching exceptions (1)
suppose we try to read data from a file:
f = o p e n( ’ m y f i l e n a m e . dat ’ , ’ r ’ )
for l i n e in f . r e a d l i n e s ():
p r i n t( l i n e )
If the file doesn’t exist, then theopen()function raises an
Input-Output Error (IOError):
I O E r r o r : [ E r r n o 2] No s u c h f i l e or d i r e c t o r y : ’ m y f i l e n a m e . dat ’
We can modify our code to catch this error:
1 try: 2 f = o p e n( ’ m y f i l e n a m e . dat ’ , ’ r ’ ) 3 e x c e p t I O E r r o r : 4 p r i n t( " The f i l e c o u l d n ’ t be o p e n e d . " ) , 5 p r i n t( " T h i s p r o g r a m s t o p s h e r e . " ) 6 i m p o r t sys 7 sys . e x i t (1) # a w a y to e x i t t h e p r o g r a m 8 9 for l i n e in f . r e a d l i n e s (): 10 p r i n t( l i n e )
which produces this message:
Catching exceptions (2)
The
try
branch (line 2) will be executed.
Should an
IOError
exception be raised the the except
branch (starting line 4) will be executed.
Should no exception be raised in the
try
branch, then the
except
branch is ignored, and the program carries on
starting in line 9.
Catching exceptions allows us to take action on errors
that occur
For the file-reading example, we could ask the user to
provide another file name if the file can’t be opened.
Catching an exception once an error has occurred may be
easier than checking beforehand whether a problem will
occur (“
It is easier to ask forgiveness than get
Raising exceptions I
Because exceptions are Python’s way of dealing with
runtime errors, we should use exceptions to report errors
that occur in our own code.
To raise a
ValueError
exception, we use
r a i s e V a l u e E r r o r ( " M e s s a g e " )and can attach a message
"Message"
(of type string) to
that exception which can be seen when the exception is
reported or caught.
For example
> > > r a i s e V a l u e E r r o r ( " S o m e p r o b l e m o c c u r e d " ) T r a c e b a c k ( m o s t 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 < module > V a l u e E r r o r : S o m e p r o b l e m o c c u r e dRaising exceptions II
Often used is the
NotImplementedError
in incremental
coding:
def m y _ c o m p l i c a t e d _ f u n c t i o n ( x ):
m e s s a g e = " F u n c t i o n c a l l e d w i t h x ={} " .f o r m a t( x )) r a i s e N o t I m p l e m e n t e d E r r o r ( msg )
If we call the function:
> > > m y _ c o m p l i c a t e d _ f u n c t i o n ( 4 2 ) T r a c e b a c k ( m o s t 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 < module >
F i l e " < stdin > " , l i n e 2 , in m y _ c o m p l i c a t e d _ f u n c t i o n N o t I m p l e m e n t e d E r r o r : F u n c t i o n c a l l e d w i t h x =42
Exercise
Extend
print line sum of file(filename)
so that if the
data file contains non-numbers (i.e. strings), these evaluate to
the value 0. For example
1 2 4 - > 7 1 cat 4 - > 5 c o f f e e - > 0
Printing: print without parentheses I
Option 1: list the variables to be printed, separated by
comma, no parentheses. Convenient, but not flexible.
This way of using
will not work with python 3.x
> > > a = 10 > > > p r i n t a 10 > > > p r i n t " The n u m b e r is " , a The n u m b e r is 10 > > > s = " h e l l o " > > > p r i n t " The n u m b e r is " , a , " and s is " , s The n u m b e r is 10 and s is h e l l o > > > p r i n t a , s # the c o m m a a d d s a s p a c e 10 " h e l l o "Printing: print with parentheses I
Option 2: construct some string
s
, then print this string
using the
function
Works with Python 2.7 and future python versions
> > > s = " I am the s t r i n g to be p r i n t e d " > > > p r i n t( s )I am the s t r i n g to be p r i n t e d
The question is, how can we construct the string
s
? We
talk about string formatting.
String formatting: the percentage (
%
) operator I
% operator syntax
Syntax:
A % B
where
A
is a string, and
B
a Python object, or a tuple of
Python objects.
The format string
A
needs to contain
k
format specifiers if the
tuple has length
k
. The operation returns a string.
Example: basic formatting of one number
> > > i m p o r t m a t h > > > p = m a t h . pi > > > " % f " % p # f o r m a t p as f l o a t (% f ) ’ 3 . 1 4 1 5 9 3 ’ # r e t u r n s s t r i n g > > > " % d " % p # f o r m a t p as i n t e g e r (% d ) ’ 3 ’ > > > " % e " % p # f o r m a t p in e x p o n e n t i a l s t y l eString formatting: the percentage (
%
) operator II
’ 3 . 1 4 1 5 9 3 e +00 ’
> > > " % g " % p # f o r m a t u s i n g f e w e r c h a r a c t e r s
’ 3 . 1 4 1 5 9 ’
The format specifiers can be combined with arbitrary
characters in string:
> > > ’ the v a l u e of pi is a p p r o x % f ’ % p ’ the v a l u e of pi is a p p r o x 3 . 1 4 1 5 9 3 ’ > > > ’ % d is my p r e f e r r e d n u m b e r ’ % 42 ’ 42 is my p r e f e r r e d n u m b e r ’
Printing multiple objects
> > > " % d t i m e s % d is % d " % (10 , 42 , 10 * 42) ’ 10 t i m e s 42 is 420 ’
> > > " pi =% f and 3* pi =% f is a p p r o x 10 " % ( p , 3* p ) ’ pi = 3 . 1 4 1 5 9 3 and 3* pi = 9 . 4 2 4 7 7 8 is a p p r o x 10 ’
Fixing width and/or precision of resulting string I
> > > ’ % f ’ % 3 . 1 4 # d e f a u l t w i d t h and p r e c i s i o n
’ 3 . 1 4 0 0 0 0 ’
> > > ’ %10 f ’ % 3 . 1 4 # 10 c h a r a c t e r s l o n g
’ 3 . 1 4 0 0 0 0 ’
> > > ’ % 1 0 . 2 f ’ % 3 . 1 4 # 10 long , 2 post - dec d i g i t s
’ 3 . 1 4 ’
> > > ’ %.2 f ’ % 3 . 1 4 # 2 post - dec d i g i t s
’ 3 . 1 4 ’
> > > ’ % . 1 4 f ’ % 3 . 1 4 # 14 post - d e c i m a l d i g i t s
’ 3 . 1 4 0 0 0 0 0 0 0 0 0 0 0 0 ’
Can also use format specifier
%s
to format strings (typically
used to align columns in tables, or such).
Common formatting specifiers
A list of common formatting specifiers, with example output
for the astronomical unit (AU) which is the distance from
Earth to Sun [in metres]:
> > > AU = 1 4 9 5 9 7 8 7 0 7 0 0 # a s t r o n o m i c a l u n i t [ m ]
> > > " % f " % AU # l i n e 1 in t a b l e
’ 1 4 9 5 9 7 8 7 0 7 0 0 . 0 0 0 0 0 0 ’
specifier
style
Example output for AU
%f
floating point
149597870700.000000
%e
exponential notation
1.495979e+11
%g
shorter of %e or %f
1.49598e+11
%d
integer
149597870700
%s
str()
149597870700
Formatted printing (% operator) I
The key idea is to create the string using the
%
operator, and
then to pass this string to the print command. Very similar
syntax exists in C and Matlab, amongst others for formatted
data output to screen and files.
Example (valid in Python 2.7 and Python 3.x) using the print
function
:
> > > i m p o r t m a t h
> > > p r i n t( " My pi = %.2 f . " % m a t h . pi ) My pi = 3 . 1 4 .
Print multiple values:
> > > p r i n t( " a =% d b =% d " % (10 , 2 0 ) ) a =10 b =20
New style string formatting (
format
method) I
A new system of built-in formatting has been proposed and is
meant to replace the old-style percentage operator formatting
(%) in the long term.
Basic ideas in examples:
Pairs of curly braces are the placeholders.
> > > " {} n e e d s {} p i n t s " .f o r m a t( ’ P e t e r ’ , 4) ’ P e t e r n e e d s 4 p i n t s ’
Can
index
into the list of objects:
> > > " {0} n e e d s {1} p i n t s " .f o r m a t( ’ P e t e r ’ ,4) ’ P e t e r n e e d s 4 p i n t s ’
> > > " {1} n e e d s {0} p i n t s " .f o r m a t( ’ P e t e r ’ ,4) ’ 4 n e e d s P e t e r p i n t s ’
New style string formatting (
format
method) II
> > > " { n a m e } n e e d s { n u m b e r } p i n t s " .f o r m a t(\ ... n a m e = ’ P e t e r ’ , n u m b e r =4) ’ P e t e r n e e d s 4 p i n t s ’
Formatting behaviour of
%f
can be achieved through
{
:f
}
, (same for
%d
,
%e
, etc)
> > > " Pi is a p p r o x {: f }. " .f o r m a t( m a t h . pi ) ’ Pi is a p p r o x 3 . 1 4 1 5 9 3 . ’
Width and post decimal digits can be specified as before:
> > > " Pi is a p p r o x { : 6 . 2 f }. " .f o r m a t( m a t h . pi ) ’ Pi is a p p r o x 3 . 1 4 . ’> > > " Pi is a p p r o x { : . 2 f }. " .f o r m a t( m a t h . pi ) ’ Pi is a p p r o x 3 . 1 4 . ’
New style string formatting (
format
method) III
This is a powerful and elegant way of string formatting.
Further Reading
Examples
http://docs.python.org/library/string.html#format-examples
What formatting should I use? I
The
.format
method most elegant and versatile
%
operator style okay, links to Matlab, C, ...
Choice partly a matter of taste
Should be aware (in a passive sense) of different possible
styles (so we can read code from others)
try to use print with parenthesis (i.e. compatible with
Python 3.x) for code you write in Python 2
Changes from Python 2 to Python 3: print I
One (maybe the most obvious) change going from Python 2
to Python 3 is that the
command loses its special
status. In Python 2, we could print ”Hello World” using
p r i n t " H e l l o W o r l d " # v a l i d in P y t h o n 2. xEffectively, we call the function
with the argument
"Hello World"
. All other functions in Python are called such
that the argument is enclosed in parentheses, i.e.
p r i n t( " H e l l o W o r l d " ) # v a l i d in P y t h o n 3. x
This is the new convention
required
in Python 3 (and
allowed
Advanced: “str“ and “repr“: “str“ I
All objects in Python should provide a method
str
which
returns a nice string representation of the object. This method
a. str ()
is called when we apply the
str
function to
object
a
:
> > > a = 3 . 1 4 > > > a . _ _ s t r _ _ () ’ 3 . 1 4 ’ > > > str( a ) ’ 3 . 1 4 ’The
str
function is extremely convenient as it allows us to
print more complicated objects, such as
> > > b = [3 , 4.2 , [ ’ a p p l e ’ , ’ b a n a n a ’ ] , (0 , 1)] > > > str( b )
Advanced: “str“ and “repr“: “str“ II
The string method
x. str
of object
x
is called implicitly,
when we
use the ”%s” format specifier in %-operator formatting to
x
use the ”
{}
” format specifier in
.format
to print
x
pass the object
x
directly to the print command
> > > p r i n t( b ) [3 , 4.2 , [ ’ a p p l e ’ , ’ b a n a n a ’ ] , (0 , 1)] > > > " % s " % b [3 , 4.2 , [ ’ a p p l e ’ , ’ b a n a n a ’ ] , (0 , 1)] > > > " {} " .f o r m a t( b ) [3 , 4.2 , [ ’ a p p l e ’ , ’ b a n a n a ’ ] , (0 , 1)]Advanced: “str“ and “repr“: “repr“ I
The
repr
function, should convert a given object into an
as accurate as possible
string representation
so that (ideally) this string can be used to re-create the
object using the
eval
function.
The
repr
function will generally provide a more detailed
string than
str
.
Applying
repr
to the object
x
will attempt to call
Advanced: “str“ and “repr“: “repr“ II
Example:
> > > i m p o r t m a t h > > > p = m a t h . pi > > > s = str( p ) # str r e p r e s e n t a t i o n of pi > > > p2 = e v a l( s ) # c o n v e r t s t r i n g to f l o a t > > > p2 3 . 1 4 1 5 9 2 6 5 3 5 9 > > > p2 - p # p2 the s a m e as p ? 2 . 0 6 9 4 5 5 7 1 7 9 0 1 2 9 1 8 e -13 # - > No > > > p3 = e v a l(r e p r( p )) > > > p3 - p # - > Yes 0.0Advanced: “str“ and “repr“: “repr“ III
We can convert an object to its
str()
or
repr()
presentation
using the format specifiers
%s
and
%r
, respectively.
> > > i m p o r t m a t h > > > " % s " % m a t h . pi ’ 3 . 1 4 1 5 9 2 6 5 3 5 9 ’ > > > " % r " % m a t h . pi ’ 3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 ’
Motivational exercise: function tables
Write a function
print x2 table()
that prints a table of
values of
f
(
x
) =
x
2for
x
= 0
,
0
.
5
,
1
.
0
, ..
2
.
5
, i.e.
0.0 0.0
0.5 0.25
1.0 1.0
1.5 2.25
2.0 4.0
2.5 6.25
Then do the same for
f
(
x
) =
x
3Then do the same for
f
(
x
) = sin(
x
)
Can we avoid code duplication?
Idea: Pass function
f
(
x
)
to tabulate to tabulating
function
Example: (
print f table.py
)
def p r i n t _ f _ t a b l e ( f ): for i in r a n g e( 6 ) : x = i * 0.5 p r i n t( " {} {} " .f o r m a t( x , f ( x ))) def s q u a r e ( x ): r e t u r n x ** 2 p r i n t _ f _ t a b l e ( s q u a r e )produces
0.0 0.0 0.5 0 . 2 5 1.0 1.0 1.5 2 . 2 5 2.0 4.0 116 / 355Can we avoid code duplication (2)?
def p r i n t _ f _ t a b l e ( f ): for i in r a n g e( 6 ) : x = i * 0.5 p r i n t( " {} {} " .f o r m a t( x , f ( x ))) def s q u a r e ( x ): r e t u r n x ** 2 def c u b i c ( x ): r e t u r n x ** 3 p r i n t( " S q u a r e " ); p r i n t _ f _ t a b l e ( s q u a r e ) p r i n t( " C u b i c " ); p r i n t _ f _ t a b l e ( c u b i c )produces:
S q u a r e 0.0 0.0 0.5 0 . 2 5 1.0 1.0 1.5 2 . 2 5 2.0 4.0 C u b i c 0.0 0.0 0.5 0 . 1 2 5 1.0 1.0 1.5 3 . 3 7 5 2.0 8.0Functions are first class objects
Functions are
first class objects
↔
functions can be given
to other functions as arguments
Example (trigtable.py):
i m p o r t m a t h f u n c s = ( m a t h . sin , m a t h . cos ) for f in f u n c s : for x in [0 , m a t h . pi / 2]: p r i n t( " { } ( { : . 3 f }) = { : . 3 f } " .f o r m a t( f . _ _ n a m e _ _ , x , f ( x ))) sin ( 0 . 0 0 0 ) = 0 . 0 0 0 sin ( 1 . 5 7 1 ) = 1 . 0 0 0 cos ( 0 . 0 0 0 ) = 1 . 0 0 0 cos ( 1 . 5 7 1 ) = 0 . 0 0 0Writing module files
Motivation: it is useful to bundle functions that are used
repeatedly and belong to the same subject area into one
module file (also called “library”)
Every Python file can be imported as a module.
If this module file has a main program, then this is
executed when the file is imported. This can be desired
but sometimes it is not.
We describe how a main program can be written which is
only executed if the file is run on its own but not if is
imported as a library.
The internal
name
variable (1)
Here is an example of a module file saved as
module1.py
:
def s o m e u s e f u l f u n c t i o n (): p a s s
p r i n t( " My n a m e is {} " .f o r m a t( _ _ n a m e _ _ ))
We can execute this module file, and the output is
My n a m e is _ _ m a i n _ _
The internal variable
name
takes the (string) value
" main "
if the program file
module1.py
is executed.
On the other hand, we can
import
module1.py
in another
file, for example like this:
i m p o r t m o d u l e 1
The output is now:
My n a m e is m o d u l e 1
This means that
name
inside a module takes the value of
The internal
name
variable (2)
In summary
name
is
" main "
if the module file is run on its
own
name
is the name (type string) of the module if the
module file is imported.
We can therefore use the following
if
statement in
module1.py
to write code that is
only run
when the module
is executed on its own:
def s o m e u s e f u l f u n c t i o n (): p a s s
if _ _ n a m e _ _ == " _ _ m a i n _ _ " :
p r i n t( " I am r u n n i n g on my own . " )
This is useful to keep test programs or demonstrations of the
abilities of a library module in this “conditional” main
Default and Keyword function
arguments
Default argument values (1)
Motivation:
suppose we need to compute the area of rectangles and
we know the side lengths
a
and
b
.
Most of the time,
b=1
but sometimes
b
can take other
values.
Solution 1:
def a r e a ( a , b ): r e t u r n a * b p r i n t( " the a r e a is {} " .f o r m a t( a r e a (3 , 1 ) ) ) p r i n t( " the a r e a is {} " .f o r m a t( a r e a (2.5 , 1 ) ) ) p r i n t( " the a r e a is {} " .f o r m a t( a r e a (2.5 , 2 ) ) )Working perfectly.
Default argument values (2)
We can reduce our efforts by providing a
default
value for
b
. We then only have to specify
b
if it is different from
this default value:
Solution 2:
def a r e a ( a , b = 1 ) : r e t u r n a * b p r i n t( " the a r e a is {} " .f o r m a t( a r e a ( 3 ) ) ) p r i n t( " the a r e a is {} " .f o r m a t( a r e a ( 2 . 5 ) ) ) p r i n t( " the a r e a is {} " .f o r m a t( a r e a (2.5 , 2 ) ) )If a default value is defined, then this parameter (here
b
)
is optional when the function is called.
Warning: default parameters have to be at the end of the
argument list in the function definition.
Keyword argument values (1)
We can call functions with a “keyword” and a value.
(The keyword is the name of the variable in the function.)
Here is an example
def f ( a , b , c ): p r i n t( " a = {} , b = {} , c = {} " .f o r m a t( a , b , c )) f (1 , 2 , 3) f ( c =3 , a =1 , b =2) f (1 , c =3 , b =2)which produces this output:
a = 1 , b = 2 , c = 3 a = 1 , b = 2 , c = 3 a = 1 , b = 2 , c = 3If we use
only
keyword arguments in the function call,
then we don’t need to know the
order
of the arguments.
(This is good.)
Keyword argument values (2)
Can combine default value arguments and keyword
arguments
Example: we use 100 subdivisions unless the user provides
a number
def t r a p e z ( f u n c t i o n , a , b , s u b d i v i s i o n s = 1 0 0 ) : # c o d e m i s s i n g h e r e i m p o r t m a t h i n t 1 = t r a p e z ( a =0 , b =10 , f u n c t i o n = m a t h . sin ) i n t 2 = t r a p e z ( b =0 , f u n c t i o n = m a t h . exp , \ s u b d i v i s i o n s =1000 , a = -0.5)Note that choosing meaningful variable names in the
function definition makes the function more user friendly.
Keyword argument values (3)
You may have met default arguments and keyword arguments
before, for example
the string method
split
uses white space as the default
value for splitting
the
open
function uses
r
(for Reading) as a default value
LAB6
Global and local variables,
Name spaces
Name spaces — what can be seen where? (1)
We distinguish between
global variables (defined in main program) and
local variables (defined for example in functions), could
be several nested layers
built-in functions
The same variablenamecan be used in a function and in the main program but they can refer to different objects and do not interfere: def f (): x = ’ I am l o c a l ’ p r i n t( x ) x = ’ I am g l o b a l ’ f () p r i n t( x )
which produces this output I am l o c a l
I am g l o b a l
Name spaces (2)
. . . so global and local variables can’t see each other?
not quite. Let’s read the small print:
If — within a function – we try to access a variable,
then Python will look for this variable
first in the local name space (i.e. within that function) then in the global name space (!)