Please check your School Email for a link to your own set of revision cards
Unit 1 Computer systems
Elements of a computer system
Computer systems in the modern world
Ethical, environmental and legal considerations
Click the image to watch an introduction to 'selection' and 'if' |
These are the codes blocks you could use |
These are the code blocks you could use |
>>> while True print 'Hello world'
File "<stdin>", line 1, in ?
while True print 'Hello world'
^
SyntaxError: invalid syntax
print
, since a colon (':'
) is missing before it. File name and line number are printed so you know where to look in case the input came from a script.>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: cannot concatenate 'str' and 'int' objects
ZeroDivisionError
, NameError
and TypeError
. The string printed as the exception type is the name of the built-in exception that occurred. This is true for all built-in exceptions, but need not be true for user-defined exceptions (although it is a useful convention). Standard exception names are built-in identifiers (not reserved keywords).Control-C
or whatever the operating system supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt
exception.>>> while True:
... try:
... x = int(raw_input("Please enter a number: "))
... break
... except ValueError:
... print "Oops! That was no valid number. Try again..."
...
try
statement works as follows.try
and except
keywords) is executed.try
statement is finished.except
keyword, the except clause is executed, and then execution continues after the try
statement.try
statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.try
statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try
statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:... except (RuntimeError, TypeError, NameError):
... pass
except ValueError, e:
was the syntax used for what is normally written asexcept ValueError as e:
in modern Python (described below). The old syntax is still supported for backwards compatibility. This means exceptRuntimeError, TypeError
is not equivalent to except (RuntimeError, TypeError):
but to except RuntimeError as TypeError:
which is not what you want.import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except ValueError:
print "Could not convert data to an integer."
except:
print "Unexpected error:", sys.exc_info()[0]
raise
try
... except
statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
else
clause is better than adding additional code to the try
clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try
... except
statement.instance.args
. For convenience, the exception instance defines __str__()
so the arguments can be printed directly without having to reference .args
.>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print type(inst) # the exception instance
... print inst.args # arguments stored in .args
... print inst # __str__ allows args to be printed directly
... x, y = inst.args
... print 'x =', x
... print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError as detail:
... print 'Handling run-time error:', detail
...
Handling run-time error: integer division or modulo by zero
raise
statement allows the programmer to force a specified exception to occur. For example:>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere
raise
indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception
).raise
statement allows you to re-raise the exception:>>> try:
... raise NameError('HiThere')
... except NameError:
... print 'An exception flew by!'
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
NameError: HiThere
Exception
class, either directly or indirectly. For example:>>> class MyError(Exception):
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return repr(self.value)
...
>>> try:
... raise MyError(2*2)
... except MyError as e:
... print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4
>>> raise MyError('oops!')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'
__init__()
of Exception
has been overridden. The new behavior simply creates the value attribute. This replaces the default behavior of creating the args attribute.class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expr -- input expression in which the error occurred
msg -- explanation of the error
"""
def __init__(self, expr, msg):
self.expr = expr
self.msg = msg
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
prev -- state at beginning of transition
next -- attempted new state
msg -- explanation of why the specific transition is not allowed
"""
def __init__(self, prev, next, msg):
self.prev = prev
self.next = next
self.msg = msg
try
statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example:>>> try:
... raise KeyboardInterrupt
... finally:
... print 'Goodbye, world!'
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>", line 2, in ?
try
statement, whether an exception has occurred or not. When an exception has occurred in the try
clause and has not been handled by an except
clause (or it has occurred in a except
or else
clause), it is re-raised after the finally
clause has been executed. The finally
clause is also executed “on the way out” when any other clause of the try
statement is left via a break
, continue
or return
statement. A more complicated example (having except
and finally
clauses in the same try
statement works as of Python 2.5):>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print "division by zero!"
... else:
... print "result is", result
... finally:
... print "executing finally clause"
...
>>> divide(2, 1)
result is 2
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
finally
clause is executed in any event. The TypeError
raised by dividing two strings is not handled by the except
clause and therefore re-raised after the finally
clause has been executed.finally
clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful.for line in open("myfile.txt"):
print line,
with
statement allows objects like files to be used in a way that ensures they are always cleaned up promptly and correctly.with open("myfile.txt") as f:
for line in f:
print line,