Download presentation
Presentation is loading. Please wait.
Published byAnita Tuula Järvenpää Modified over 5 years ago
1
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Winter 2019 CISC101 4/11/2019 CISC101 Reminders Assignment 3 due next Friday. Winter 2019 CISC101 - Prof. McLeod Prof. Alan McLeod
2
Today Exceptions. Introduce Functions. Winter 2019
Winter 2019 CISC101 4/11/2019 Today Exceptions. Introduce Functions. Winter 2019 CISC101 - Prof. McLeod Prof. Alan McLeod
3
File Read and Write Errors
Suppose a problem occurs: File does not exist. Folder does not exist. You do not have read or write access in the folder you are attempting to use. Access fails partway through a read or write attempt. Any of these problems will result in the throwing of an exception, which we will see as an error message after our program crashes. Winter 2019 CISC101 - Prof. McLeod
4
File Read and Write Errors, Cont.
Suppose we could catch the exception before it crashes the program? It would give us a chance to fix the problem and try again. A try/except structure can be used to catch exceptions: See RobustFileInput.py Winter 2019 CISC101 - Prof. McLeod
5
Back To: The .index() List Method
This method returns the index location of the first match to the supplied argument in a list. What does the method do if it cannot find a match? Winter 2019 CISC101 - Prof. McLeod
6
.index() List Method, Cont.
How can you prevent this method from crashing your program? Two possibilities: Use the in keyword to see if the value is in the list at all, then invoke .index to find the location: if 100 in randNums : print(randNums.index(100)) else : print("100 is not in the list!") Winter 2019 CISC101 - Prof. McLeod
7
.index() List Method, Cont.
The problem with this is that it is “costly” – you have to search through the list twice. How about letting the error occur, but prevent it from crashing your program and then allow the program to carry on? Again, use a try-except construct. Winter 2019 CISC101 - Prof. McLeod
8
CISC101 Exceptions BIFs and methods throw exceptions as a means of indicating that they cannot do their job. Kind of like a temper tantrum! Observed as all that red coloured font when your program crashes: Winter 2019 CISC101 - Prof. McLeod Prof. Alan McLeod
9
What is an Exception? What do you see if you try something like:
print(int("Hello!")) >>> print(int("Hello")) Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> print(int("Hello")) ValueError: invalid literal for int() with base 10: 'Hello' Winter 2019 CISC101 - Prof. McLeod
10
What is an Exception?, Cont.
A syntax error is what you get when your syntax cannot be recognized by the interpreter. All other errors occur when your code is running. An exception is a run-time error. Every run-time error in Python has a name – this is the type of the exception. For a list of exception types see “Built-in Exceptions” in the Python Standard Library documentation. The example on the previous slide was a “ValueError” exception. Winter 2019 CISC101 - Prof. McLeod
11
Crash Prevention! Normally an exception is what you see when your program has crashed from a fatal error. Better programs catch exceptions before this happens! Or – they make sure the exception will never occur by checking for error conditions ahead of time! Catching exceptions gives you a chance to fix the problem. You catch exceptions using try-except statements: Winter 2019 CISC101 - Prof. McLeod
12
Catching Exceptions Syntax for a simple try-except statement: try :
try_statements except Exception : except_statements Exception is the name of the exception you are catching. Winter 2019 CISC101 - Prof. McLeod
13
Catching Exceptions, Cont.
try : try_statements except Exception : except_statements try_statements is a section of code that could generate a run-time error (an exception). The code here stops as soon as there is an error. except_statements is the code that will execute if the exception is generated. Winter 2019 CISC101 - Prof. McLeod
14
Catching Exceptions, Cont.
How to figure out which exception(s) to catch? Observe the error generated (your program crashes!) and get the name of the exception from the traceback listing. Or look in the Python docs. Winter 2019 CISC101 - Prof. McLeod
15
Catching Exceptions, Cont.
Suppose your code could generate more than one kind of exception? You can be prepared to catch more than one: try : try_statements except Exception1: except_statements except Exception2 : … Winter 2019 CISC101 - Prof. McLeod
16
Catching Exception, Cont.
Sometimes you should not catch exceptions, but should prevent them from happening in the first place by using preventative code. See WhichIsBetter.py Winter 2019 CISC101 - Prof. McLeod
17
.index() List Method, Cont.
In the case of this method, catching the exception is a less costly (ie. faster!) way of preventing a crash if the method fails. Can you use any (easy) preventative code to keep int() from crashing when it is supplied with a non-numeric string? How about float()? Winter 2019 CISC101 - Prof. McLeod
18
CISC101 Demo – Robust Input Until now, we have had to assume the user enters a number when we tell him to. Very trusting of us! Now we don’t have to – he can be a monkey and our input won’t crash! See MoreRobust.py Winter 2019 CISC101 - Prof. McLeod Prof. Alan McLeod
19
Assignment 1, Part A – Mortgage Calculator
Let’s add robust input code to the solution for this part of the assignment to make input completely robust. Compensate for non-numeric input as well as checking for the number being between legal limits. See: RobustMortgageCalculator.py Can you crash this program? Winter 2019 CISC101 - Prof. McLeod
20
Mortgage Calculator, Cont.
Do the three sections of code that obtain the input look similar to you? What are the differences between these three sections of code? The prompt and the two limits. What does each section produce, when it is done? It would be nice if we only needed to write this section once! Winter 2019 CISC101 - Prof. McLeod
21
Functional Input Version
Move one copy of this input section into a separate function. Make the function general enough so that it can work for all three inputs. The different prompts and limits will be supplied as arguments to the function. The function will return the number obtained. See FunctionalMortgageCalculator.py Winter 2019 CISC101 - Prof. McLeod
22
Functional Input Version, Cont.
Shorter program! Input code is all in one place – changes only need to be made in one place, instead of three places. Prevents repetitious code. (Our new function could be used by other programs: Put it in a code module and import it into other programs, just like we have been doing with the turtle and math modules. (Later)) Winter 2019 CISC101 - Prof. McLeod
23
Function Syntax def fcnName (no parameters, one or many parameters separated by commas) : # code indented inside the function, parameters being # used anywhere inside the function # including return statement(s): return nothing or something We have already been defining a function – main(). Winter 2019 CISC101 - Prof. McLeod
24
Modular Version of the “Game of Pig”
Take a critical look at the Assignment 2 sample solution. Can the use of functions improve this program? See FunctionalGameOfPig.py. Winter 2019 CISC101 - Prof. McLeod
25
Function Mechanics When invoking a function, you may need to supply argument(s) inside the ( ) after the function name. These arguments are mapped to the function’s parameters, which hold the argument values for use inside the function. A function may return a value (or a collection of values) which will end up being used in the code that invoked the function. A function is one aspect of code “Modularity”: Winter 2019 CISC101 - Prof. McLeod
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.