MIME-Version: 1.0 Content-Location: file:///C:/F48430D8/Week8.htm Content-Transfer-Encoding: quoted-printable Content-Type: text/html; charset="us-ascii"
Week =
8
Exception handling and optional arguments
Computer Science A202 /
A598
and=
span> Informatics I211
This
week’s success strategy
<=
![if !supportLists]>n
It's not just how
hard your work, or how smart you are, it's how smart you work!
<=
![if !supportLists]>q
Different people,=
and
different problems, require very different kinds of thinking.
<=
![if !supportLists]>q
Think about how
they're thinking.
<=
![if !supportLists]>q
Research has shown
that developing this ability is one of the most valuable things you can lea=
rn
in college.
<=
![if !supportLists]>n
You'll probably
discover things like the following:
<=
![if !supportLists]>q
Your mind works b=
est
when you're thoroughly rested.
<=
![if !supportLists]>n
Recent research h=
as
shown that even mild sleep deprivation, of the kind most students experience
most of the time, significantly reduces cognitive ability.
<=
![if !supportLists]>n
Notice that some
kinds of work you can do satisfactorily when you're a bit tired, but others=
are
much harder then.
<=
![if !supportLists]>q
It helps to draw
pictures.
<=
![if !supportLists]>q
Try printing your
program when you're really stuck.
<=
![if !supportLists]>q <=
/span>Sometimes thinking works much better when you're not working at it! =
If
you're stuck, take a break.
Excep=
tion
handling: syntax
<=
![if !supportLists]>n Exceptions
can be caught and handled as desired using the try/except statement
<=
![if !supportLists]>n Statement
syntax (simplified):
try:
<try body>
except [ <exception type> ] :
<handler body>
+R=
30;
<=
![if !supportLists]>q <=
/span>the optional <exception type> may be an
exception class name or a string literal (the latter is deprecated)
<=
![if !supportLists]>q <=
/span>+… means that there may be one or more except
clauses
Excep=
tion
handling: semantics
<=
![if !supportLists]>n =
span>Try statement semantics (simplified):
<=
![if !supportLists]>q <=
/span>execute <try body>
<=
![if !supportLists]>q <=
/span>if an exception is raised that is not caught by another exception
handler, and its type (or string literal) matches one of the except clauses
<exception type>s, the corresponding <handler body> is executed=
<=
![if !supportLists]>q <=
/span>an except clause with no <exception type> catches all exceptio=
ns
<=
![if !supportLists]>q <=
/span>execution continue after the try statement when the <handler body=
>
completes
<=
![if !supportLists]>n =
span>An exception caught by a try/except statement may =
be
raised by any code executed by its body, including code called by the body,
directly or indirectly
<=
![if !supportLists]>q <=
/span>function calls and entry into a <try body> add a frame to the
"call stack" that is removed when the function returns or body
execution completes
<=
![if !supportLists]>q <=
/span>when an exception is raised, the call stack is "popped" un=
til
a try body frame is encountered with a matching catch clause
<=
![if !supportLists]>n =
span>Exceptions may be raised either by system operatio=
ns,
if an error is detected, or by program code executing a raise statem=
ent
Common
built-in exceptions
<=
![if !supportLists]>n Some
of the more common system exceptions types:
<=
![if !supportLists]>q <=
/span>ValueError: an
operation received a value of the right type, but an inappropriate value not
covered by a more specific exception type
<=
![if !supportLists]>q <=
/span>NameError: a
variable could not be found
<=
![if !supportLists]>q <=
/span>TypeError: an
operation was given an argument of the wrong type
<=
![if !supportLists]>q <=
/span>SyntaxError: bad
expression or statement syntax encountered, for example during an import=
,
eval, or input operation
<=
![if !supportLists]>q <=
/span>IndexError: an =
index
was out of range
<=
![if !supportLists]>q
AttributeError: an attempt was made to access an object attribute
(field or method) that does not exist in the object
<=
![if !supportLists]>q
Exception<=
/b>: the catch-all for all system exceptions and
non-deprecated user exceptions
Excep=
tion
handling tips
<=
![if !supportLists]>n Put
a try statement where the program is prepared to continue after dealing with
the exceptions it handles
<=
![if !supportLists]>q <=
/span>remember: when an <handler block> completes,=
the
program continues after the try statement
<=
![if !supportLists]>n In
most program environments, if an exception is not caught, a stack trace is
printed and the program terminates
<=
![if !supportLists]>q <=
/span>the stack trace first indicates the method calls t=
hat
were popped off the call stack by the exception
<=
![if !supportLists]>q <=
/span>it then prints the name of the exception and any
additional information associated with it
Excep=
tion
handling example
def inputNumbers():
'''Interactively enter a list=
of
numbers and return
them in a list.'''
lst =3D []
print 'Just press <Enter> if there are no more
values.'
while True:
value =3D raw_input('Value: ')
if value =3D=3D '':
=
break
try:
=
i =3D int(value)
except ValueError:
=
print 'Bad value'
=
continue
lst.append(i)
return lst
Funct=
ions
with optional arguments (not in text)
<=
![if !supportLists]>n =
span>Some functions have optional arguments
<=
![if !supportLists]>q <=
/span>Examples (taken from the on-line documentation):
built-in open(filename[, mode[, bufsize]])
string split(s[, sep[, maxsplit]])
built-in max(s[, args...])
<=
![if !supportLists]>n
With a single argument =
s,
return the largest item of a non-empty sequence (such as a string, tuple or
list). With more than one argument, return the largest of the arguments.
<=
![if !supportLists]>n =
span>"Rest" parameter declarations
<=
![if !supportLists]>q <=
/span>syntax: precede the last formal parameter by an asterisk
<=
![if !supportLists]>q <=
/span>semantics: the last formal parameter is bound to a tuple of the
remaining arguments
<=
![if !supportLists]>q <=
/span>example:
>>>
def fun(firstArg, *restArgs):
print firstArg, restArgs
>>>
fun(1, 2, 3)
1
(2, 3)
>>>
fun(1)
1
()
Keywo=
rd
parameters: introduction (not in text)
<=
![if !supportLists]>n &nb=
sp; Keyword parameters allow actual parameters (in function calls) to be
named
<=
![if !supportLists]>q =
span>advantages
<=
![if !supportLists]>n &nb=
sp;
no need to remember the
order of arguments
<=
![if !supportLists]>n &nb=
sp;
keyword parameter names
help document their meaning
<=
![if !supportLists]>n &nb=
sp;
keyword parameters may =
be
omitted and given default values
<=
![if !supportLists]>q =
span>disadvantage: makes code more bulky and cluttered <=
![if !supportLists]>n &nb=
sp; Example >>> def fun(a, b=3D1, c=3D2): print a, b, c >>> fun(0, 5, 6) 0 5 6 >>> fun(0, 5) 0 5 2 >>> fun(0, c=3D8) 0 1 8 >>> fun(1, c=3D8, b=3D4) 1 4 8 >>> fun(c=3D9) ... TypeError: fun() takes at least 1 non-key=
word
argument (0 given) Keywo=
rd
parameters: in general <=
![if !supportLists]>n =
span>Optional arguments can be named with keywords <=
![if !supportLists]>q <=
/span>any variable name may be used as an argument keyword <=
![if !supportLists]>n &nb=
sp; not the limited set of Python syntax keywords <=
![if !supportLists]>n =
span>Keyword formal parameter declarations <=
![if !supportLists]>q <=
/span>syntax: <keyword> =3D <default value expression> <=
![if !supportLists]>q <=
/span>semantics: if the argument is omitted, the parameter is given the
default value <=
![if !supportLists]>q <=
/span>the corresponding actual parameter may either use the same keyword or
use no keyword and be in the same position <=
![if !supportLists]>n =
span>Keyword actual parameters <=
![if !supportLists]>q <=
/span>syntax: <keyword> =3D <argument value expression> <=
![if !supportLists]>n &nb=
sp; must follow all non-keyword parameters <=
![if !supportLists]>q <=
/span>semantics: the parameter with the same keyword is given bound to the
value of <argument value expression> <=
![if !supportLists]>n =
span>Avoid combining keyword and "rest" argum=
ents
in the same function Operating system
commands with named arguments <=
![if !supportLists]>n =
span>Operating system commands frequently have named
arguments <=
![if !supportLists]>q
often called switche=
s
or options <=
![if !supportLists]>q <=
/span>usually prefixed by a dash in Unix and a slash in Windows <=
![if !supportLists]>q <=
/span>some have an associated value in the following argument position <=
![if !supportLists]>q <=
/span>some have no associated value <=
![if !supportLists]>n &nb=
sp; they are essentially boolean valued <=
![if !supportLists]>q <=
/span>they usually come before required or "rest" =
arguments <=
![if !supportLists]>n =
span>Examples <=
![if !supportLists]>q
Window: dir /s /b <=
![if !supportLists]>n &nb=
sp; /s lists files in subdirectories as well <=
![if !supportLists]>n &nb=
sp; /b lists only file names (not modification date,
protection info, etc) <=
![if !supportLists]>q
Unix: ls -l -t <=
![if !supportLists]>n &nb=
sp; -l is a long list, with file modification time,
protection info, etc. <=
![if !supportLists]>n
-t
The <=
b>python
command
>python -h
usage: C:\cygwin\usr\local\bin\python.exe [option] ... [-c cmd | file | -]
[arg] ...
Options and arguments (and corresponding environment variables):
-c cmd : program passed in as string
(terminates option list)
-d :=
debug
output from parser (also PYTHONDEBUG=3Dx)
-E :
ignore environment variables (such as PYTHONPATH)
-h :=
print
this help message and exit
-i :
inspect interactively after running script, (also PYTHONINSPECT=3Dx)
and force prompts, even if stdin does not
appear to be a terminal
-O :
optimize generated bytecode (a tad; also PYTHONOPTIMIZE=3Dx)
-OO : remo=
ve
doc-strings in addition to the -O optimizations
-Q arg : division options: -Qold (default=
),
-Qwarn, -Qwarnall, -Qnew
-S :=
don't
imply 'import site' on initialization
-t :=
issue
warnings about inconsistent tab usage (-tt: issue errors)
-u :
unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=3Dx)
see man page for details on internal buff=
ering
relating to '-u'
-v :
verbose (trace import statements) (also PYTHONVERBOSE=3Dx)
-V :=
print
the Python version number and exit
-W arg : warning control (arg is
action:message:category:module:lineno)
-x :=
skip
first line of source, allowing use of non-Unix forms of #!cmd
file : program read =
from
script file
- :
program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH :
';'-separated list of directories prefixed to the
=
default module search path. The result is sys.path.
PYTHONHOME : alt=
ernate
<prefix> directory (or <prefix>;<=
exec_prefix>).
=
The default module search path uses <prefix>\lib.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
Optio=
nal
and keyword argument exercise
<=
![if !supportLists]>n =
span>Exercise: define a function printArgs that
takes any number of arguments and prints the value of each on a separate li=
ne
<=
![if !supportLists]>n =
span>Answer:
def printArgs(*args):
for arg in args:
print arg
<=
![if !supportLists]>n =
span>Exercise: define a function
>>> inGradeRange(100=
)
True
>>> inGradeRange(101=
)
False
>>> inGradeRange(101,
max=3D110)
True
>>> inGradeRange(10,
min=3D12)
False
<=
![if !supportLists]>n =
span>Answer:
def inGradeRange(grade, min=
=3D0,
max=3D100):
return min <=3D gra=
de <=3D
max