Unit 5
Exceptions
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Catching exceptions
Whenever a runtime error occurs, it creates an exception
object.
The program stops running at this point and Python prints out
the traceback, which ends with a message describing the
exception that occurred.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Catching exceptions
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Catching exceptions
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Catching exceptions
➢In each case, the error message on the last line has two
parts:
▪ The type of error before the colon, and
▪Specifics about the error after the colon.
➢Sometimes we want to execute an operation that might
cause an exception, but we don’t want the program to stop.
➢We can handle the exception using the try statement to
“wrap” a region of code.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Catching exceptions
➢Example:Trying to open a file that do not exist
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Catching exceptions
The try statement has three separate clauses:
1. try ...
2. except ...
3. finally.
➢Either the except or the finally clauses can be omitted, so the
above code considers the most common version of the try
statement first.
➢The try statement executes and monitors the statements in
the first block.
➢ If no exceptions occur, it skips the block under the except
clause.
➢ If any exception occurs, it executes the statements in the
except clause
Akshata S Bhayyar,and then
Asst. Prof. continues.
Dept. of CSE, RIT
Catching exceptions
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Catching exceptions
The function we’ve just shown is not one we’d recommend.
It opens and closes the file, which is semantically different from
asking “does it exist?”.
How?
Firstly, it might update some timestamps on the file.
Secondly, it might tell us that there is no such file if some other
program already happens to have the file open, or if our
permission settings don’t allow us to open the file.
Python provides a module called os.path within the os module.
It provides a number of useful functions to work with paths, files
and directories,
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Catching exceptions
➢We can use multiple except clauses to handle different
kinds of exceptions.
So the program could do one thing if the file does
not exist, but do something else if the file was in use by
another program.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Raising our own exceptions
If our program detects an error condition, we can raise an
exception.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Raising our own exceptions
ValueError is one of the built-in exception types which most
closely matches the kind of error we want to raise.
The complete listing of built-in exceptions can be found at the
Built-in Exceptions section of the Python Library Reference ,
again by Python’s creator, Guido van Rossum.
The error message includes the exception type and the
additional information that was provided when the exception
object was first created.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The finally clause of the try statement
The finally block will always be executed, no matter if the try
block raises an error or not:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Strings
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
A compound data type
So far we have seen built-in types like int, float, bool, str and
we’ve seen lists and pairs.
Strings, lists, and pairs are qualitatively different from the others
because they are made up of smaller pieces.
In the case of strings, they’re made up of smaller strings each
containing one character.
Types that comprise smaller pieces are called compound data
types
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Working with strings as single things
A string is also an object. So each string instance has its own
attributes and methods.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Working with strings as single things
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Working with strings as single things
ss = "Hello, World!"
tt = ss.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Working with strings as single things
When you type the name of the method, some further help about
its parameter and return type, and its docstring, will be
displayed.
This is a good example of a tool PyScripter using the meta-
information the docstrings provided by the module
programmers.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Working with the parts of a string
The indexing operator (Python uses square brackets to enclose
the index) selects a single character substring from a string:
fruit = "banana"
m = fruit[1]
print(m)
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Working with the parts of a string
We can use enumerate to visualize the indices:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Length
The len function, when applied to a string, returns the number of
characters in a string:
To get the last letter of a string, you might be tempted to try
something like this:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Length
Alternatively, we can use negative indices, which count backward
from the end of the string. The expression fruit[-1] yields the last
letter, fruit[-2] yields the second to last, and so on.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Traversal and the for loop
A lot of computations involve processing a string one character at
a time. Often they start at the beginning, select each character in
turn, do something to it, and continue until the end. This pattern
of processing is called a traversal.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Traversal and the for loop
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Concatenating Two Strings
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Slices
A substring of a string is obtained by taking a slice. Similarly, we
can slice a list to refer to some sublist of the items in the list:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Slices
The operator [n:m] returns the part of the string from the n’th
character to the m’th character, including the first but excluding
the last.
This behaviour makes sense if you imagine the indices pointing
between the characters, as in the following diagram:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Slices
Three tricks are added to this:
a. If you omit the first index (before the colon), the slice starts at
the beginning of the string (or list).
b. If you omit the second index, the slice extends to the end of the
string (or list).
c. Similarly, if you provide value for n that is bigger than the
length of the string (or list), the slice will take all the values up
to the end. (It won’t give an “out of range” error like the normal
indexing operation does.)
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
String comparison
The comparison operators work on strings. To see if two strings
are equal:
Other comparison operations are useful for putting words in
lexicographical order:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
String comparison
This is similar to the alphabetical order you would use with a
dictionary, except that all the uppercase letters come before all
the lowercase letters.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Strings are immutable
It is tempting to use the [] operator on the left side of an
assignment, with the intention of changing a character in a string.
For example:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Strings are immutable
The solution here is to concatenate a new first letter onto a slice
of greeting. This operation has no effect on the original string.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The in and not in operators
The in operator tests for membership. When both of the
arguments to in are strings, in checks whether the left argument
is a substring of the right argument.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The in and not in operators
Note that a string is a substring of itself, and the empty string is a
substring of any other string. (Also note that computer scientists
like to think about these edge cases quite carefully!)
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The in and not in operators
The not in operator returns the logical opposite results of in:
Combining the in operator with string concatenation using +, we
can write a function that removes all the vowels from a string:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
A find function
What does the following function do?
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Looping and counting
The following program counts the number of times the letter a
appears in a string, and is another example of the counter pattern
introduced in Counting digits:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Optional parameters
To find the locations of the second or third occurrence of a
character in a string, we can modify the find function, adding a
third parameter for the starting position in the search string:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Optional parameters
The call find("banana", "a", 2) now returns 3, the index of the
first occurrence of “a” in “banana” starting the search at index 2.
What does find("banana", "n", 3) return?
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Optional parameters
When a function has an optional parameter, the caller may
provide a matching argument.
If the third argument is provided to find, it gets assigned to start.
But if the caller leaves the argument out, then start is given a
default value indicated by the assignment start=0 in the function
definition.
So the call find("banana", "a", 2) to this version of find behaves
just like find2, while in the call find("banana", "a"), start will be
set to the default value of 0.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Optional parameters
Adding another optional parameter to find makes it search from a
starting position, up to but not including the end position:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Optional parameters
The optional value for end is interesting: we give it a default value
None if the caller does not supply any argument.
In the body of the function we test what end is, and if the caller did
not supply any argument, we reassign end to be the length of the
string.
If the caller has supplied an argument for end, however, the caller’s
value will be used in the loop.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Optional parameters
The semantics of start and end in this function are precisely the
same as they are in the range function.
Here are some test cases that should pass:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The built-in find method
Now that we’ve done all this work to write a powerful find function,
we can reveal that strings already have their own built-in find method.
It can do everything that our code can do, and more!
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The built-in find method
The built-in find method is more general than our version. It can
find substrings, not just single characters:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The split method
It splits a single multi-word string into a list of individual words,
removing all the whitespace between them. (Whitespace means
any tabs, newlines, or spaces.)
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Cleaning up your strings
Strings are immutable, so we cannot change the string with the
punctuation — we need to traverse the original string and create
a new string, omitting any punctuation:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Cleaning up your strings
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Cleaning up your strings
Composing together this function and the split method
we’ll clean out the punctuation, and split will clean out the
newlines and tabs while turning the string into a list of words:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Cleaning up your strings
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
Output
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The string format method
The easiest and most powerful way to format a string in Python
3 is to use the format method.
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The string format method
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The string format method
▪Each of the replacement fields can also contain a format
specification it is always introduced by the : symbol
▪This modifies how the substitutions are made into the
template, and can control things like:
✓whether the field is aligned to the left <, center ^, or right >
✓the width allocated to the field within the result string (a number
like 10)
✓the type of conversion
✓if the type conversion is a float, you can also specify how many
decimal places are wanted (typically, .2f is useful for working with
currencies to two decimal places.)
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The string format method
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The string format method
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The string format method
You can have multiple placeholders indexing the same argument,
or perhaps even have extra arguments that are not referenced at
all:
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT
The string format method
Akshata S Bhayyar, Asst. Prof. Dept. of CSE, RIT