Presentation is loading. Please wait.

Presentation is loading. Please wait.

Winter 2018 CISC101 12/1/2018 CISC101 Reminders

Similar presentations


Presentation on theme: "Winter 2018 CISC101 12/1/2018 CISC101 Reminders"— Presentation transcript:

1 Winter 2018 CISC101 12/1/2018 CISC101 Reminders Quiz 3 this week in lab. Topics in slides from last Tuesday. Turtle not on quiz. Keyword and Default Arguments on quiz. Winter 2018 CISC101 - Prof. McLeod Prof. Alan McLeod

2 Today Functions: Checking argument types.
Making our input function even more robust and flexible. Raising Exceptions. Start Strings. Winter 2018 CISC101 - Prof. McLeod

3 Checking Argument Types
A disadvantage of loosely typed language like Python is that the interpreter cannot check to make sure that you are supplying the proper argument types to a function. Improper argument types will result in a run-time error unless the function itself checks. What should the function do if argument types are not correct? Winter 2018 CISC101 - Prof. McLeod

4 Checking Argument Types, Cont.
CISC101 Checking Argument Types, Cont. A function that expects a number for an argument might get a string (or something else!) instead. Ouch! So, a *very* robust function will check argument types. For example if numArg is supposed to be a number, check to see if: type(numArg) == type(1) or type(numArg) == type(1.1) or, simply: type(numArg) == int or type(numArg) == float is True. Winter 2018 CISC101 - Prof. McLeod Prof. Alan McLeod

5 isinstance() Another BIF that you can use to check types. For example:
>>> aVal = 1234 >>> isinstance(aVal, int) True >>> isinstance(aVal, str) False Winter 2018 CISC101 - Prof. McLeod

6 Most! Robust Input Function
See the mrInput module, and the program testMrInput.py. If the lowLimit and highLimit values are reversed then just switch them. What to do if they are the same? Winter 2018 CISC101 - Prof. McLeod

7 Summary, So Far Keyword arguments allow you some flexibility in how you supply arguments when invoking a function. Default arguments are used in a function definition and assign default values to parameters that do not have to be mapped when the function is invoked. Other languages (like Java) use method overloading to provide this flexibility. Winter 2018 CISC101 - Prof. McLeod

8 Summary So Far, Cont. Checking arguments can be a bit more strenuous in a dynamically typed language like Python – you need to check types as well as values. None can be assigned to a variable or a parameter when you cannot assign a real value. You can check for == None or != None, but that’s all you can do! Winter 2018 CISC101 - Prof. McLeod

9 Last Resort for Functions
Our input function was able to handle any combination of messed up arguments and still do something sensible. But suppose a function encounters a difficulty that it cannot repair. What does it do? Raises an Exception! Winter 2018 CISC101 - Prof. McLeod

10 Raising Exceptions Sometimes a function just has to fail.
(Like the .index() method when the string cannot be found.) Until now: def aFunction(aParam) : if aParam == "fail" : print("I am sorry, but I cannot continue!") return else : return len(aParam) Winter 2018 CISC101 - Prof. McLeod

11 Raising Exceptions, Cont.
Assuming that the function cannot repair the problem, it just has to exit. This is kind of lame: What happens if the invoking function is expecting a return value? It is not wise and often not even possible to simply return some sort of magic error code that can be used by the invoking function to detect a problem. Do different functions have different error codes? How else can the invoking function know the function that it just called could not do its job? Winter 2018 CISC101 - Prof. McLeod

12 Raising Exceptions, Cont.
The exception mechanism is a much better way of allowing a function to “abort”: No worries about the function returning something. In fact the whole return thing is irrelevant – the function never gets to return anything and the statement expecting the return value in the invoking function never has a chance to finish. The existence of an error condition is made very clear to the invoking function. The invoking function can catch the exception – maybe it will be able to fix the problem? This mechanism is an expected part of most modern programming languages. Winter 2018 CISC101 - Prof. McLeod

13 Raising Exceptions, Cont.
Do this instead: def aFunction(aParam) : if aParam == "fail" : raise ValueError("The fail argument!") else : return len(aParam) Winter 2018 CISC101 - Prof. McLeod

14 Raising Exceptions, Cont.
raise ValueError("The fail argument!") The raise keyword “raises” or “throws” the exception. The function immediately stops after the raise command is executed. You must raise an exception object – typically you would use one already defined in Python. ValueError is a good general purpose exception. And, supply a relevant message to the exception as a string literal. Winter 2018 CISC101 - Prof. McLeod

15 Raising Exceptions, Cont.
Of course if the exception is not caught, we see: Traceback (most recent call last): File "C:/Users/Alan/Teaching/CISC101/2016Winter/Code/SecondHalf/FailingFunction.py", line 10, in <module> main() File "C:/Users/Alan/Teaching/CISC101/2016Winter/Code/SecondHalf/FailingFunction.py", line 8, in main print(aFunction("fail")) File "C:/Users/Alan/Teaching/CISC101/2016Winter/Code/SecondHalf/FailingFunction.py", line 3, in aFunction raise ValueError("The fail argument!") ValueError: The fail argument! Winter 2018 CISC101 - Prof. McLeod

16 Raising Exceptions, Cont.
If we don’t want to see all that, then the function needs to be invoked in a try/except construct. Which we know how to do… Even if you cannot fix the problem at least the try/except structure gives you a chance to exit your program gracefully, without the user seeing all the red stuff! Winter 2018 CISC101 - Prof. McLeod

17 Aside - Getting the Message Out
You can extract the message from an exception with a slightly modified try/except construct: try : print(aFunction("fail")) except ValueError as message : print("Exception message:", message) Would show this to the console: Exception message: The fail argument! Winter 2018 CISC101 - Prof. McLeod

18 Raising Exceptions, Cont.
You can have as many raise statements inside a function as you need – use the same exception, but provide different messages, so the user of your function has a better idea of what the specific error is. In assignment 4, you raise a ValueError, but you also need to be prepared to catch this one and the OSError exception raised by the open() BIF. Winter 2018 CISC101 - Prof. McLeod

19 CISC101 Strings String manipulation is a frequent activity in any programming language: Web site construction / analysis. Speech analysis. Text searching and indexing. Spell and grammar checkers. Program (code) interpretation. Scanning s for SPAM. NSA… A string is a kind of data structure – like a tuple, but they have lots of methods (tuples don’t)! Winter 2018 CISC101 - Prof. McLeod Prof. Alan McLeod

20 Help With String Methods
More detail in section of the Python Standard Library help docs. Or look up “string” then “methods” in the index. Winter 2018 CISC101 - Prof. McLeod

21 Strings, so Far… What do we know, so far? String literals:
"Hello there! ", or 'Hey man!', or """Multiline string""" You can store a string in a variable, just like anything else. They are of type str. A conversion BIF to create strings: str( ). Winter 2018 CISC101 - Prof. McLeod

22 Strings, so Far, Cont. A BIF to input a string from the keyboard:
You can put escape sequences like: \n, \”, \’, \\, \t in a string to control how a string is displayed. The string format() method is used to help format numeric output for display. Or you can use “formatted strings” that have the f at the beginning. Winter 2018 CISC101 - Prof. McLeod

23 Strings, so Far, Cont. You can concatenate strings using +.
You can generate repeating strings using *. You can compare strings using ==, >, <, >=, <= and != (just like comparing numbers, but you must have a string on both sides of the operator). Note that == and != will work with mixed types (but so what?). Strings are compared on the basis of the ASCII code values for their individual characters. Winter 2018 CISC101 - Prof. McLeod

24 Characters, so Far The Unicode character value takes two bytes of memory for a value between 0x0000 and 0xFFFF. Python uses Unicode already. The ASCII system only uses one byte. Keyboard characters form the lower half of the ASCII character set. “Extended ASCII” characters occupy the upper half. Strings are immutable collections of characters. Winter 2018 CISC101 - Prof. McLeod

25 Strings, so Far, Cont. Like other collections we have found that the following also work with strings: The slice operator [ : ] in and not in work with strings as long as a string is placed on both sides. for loops work with strings. len() works with strings. list() and tuple() will create a list or a tuple consisting of the individual characters from the string. sorted() returns a sorted list of individual characters. reversed() and enumerate() also work (along with a for loop). (See StringDemo.py) Winter 2018 CISC101 - Prof. McLeod

26 Strings vs Tuples Strings are immutable like Tuples:
Cannot put the slice operator on the left side of the assignment operator. del does not work. But, Tuples only have two methods – count() and index(). Strings have many methods – 44 of them! Winter 2018 CISC101 - Prof. McLeod

27 Characters What strings are made of!
CISC101 Characters What strings are made of! In Python, a character literal is just a string of length one. A Character has to be stored as a numeric value in RAM (how else?). So, we need to know which numeric values stand for which characters. Thus the Unicode system which needs a two-byte number to store the character’s numeric code. Winter 2018 CISC101 - Prof. McLeod Prof. Alan McLeod

28 Character BIFs chr() takes an integer argument, which is the Unicode number and returns the corresponding character. This number can range from 0x0000 to 0xFFFF ( , 2 bytes, compared to ASCII’s 1 byte). ord() does the reverse of chr() returning the character code value, given a single character as a string. Winter 2018 CISC101 - Prof. McLeod


Download ppt "Winter 2018 CISC101 12/1/2018 CISC101 Reminders"

Similar presentations


Ads by Google