Winter 2018 CISC101 12/1/2018 CISC101 Reminders

Slides:



Advertisements
Similar presentations
Introduction to Python
Advertisements

CS190/295 Programming in Python for Life Sciences: Lecture 3 Instructor: Xiaohui Xie University of California, Irvine.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Built-in Data Structures in Python An Introduction.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Today… Style, Cont. – Naming Things! Methods and Functions Aside - Python Help System Punctuation Winter 2016CISC101 - Prof. McLeod1.
Today… The for loop. Introducing the Turtle! Loops and Drawing. Winter 2016CISC101 - Prof. McLeod1.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
Next Week… Quiz 2 next week: –All Python –Up to this Friday’s lecture: Expressions Console I/O Conditionals while Loops Assignment 2 (due Feb. 12) topics:
Today… Loops and Drawing, Cont. –Two slightly more advanced demos. Collections Overview. Winter 2016CISC101 - Prof. McLeod1.
Introduction to Python
Why exception handling in C++?
CMPT 120 Topic: Python strings.
CISC124 Labs start this week in JEFF 155: Meet your TA.
Exceptions and files Taken from notes by Dr. Neil Moore
Fall 2017 CISC124 9/21/2018 CISC124 First onQ quiz this week – write in lab. More details in last Wednesday’s lecture. Repeated: The quiz availability.
CISC101 Reminders Quiz 2 this week.
CISC101 Reminders Quiz 2 this week.
CISC101 Reminders Assn 3 due Friday, this week.
Winter 2018 CISC101 11/16/2018 CISC101 Reminders
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Winter 2018 CISC101 11/22/2018 CISC101 Reminders
CISC101 Reminders Quiz 1 grading underway Assn 1 due Today, 9pm.
CISC101 Reminders Slides have changed from those posted last night…
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
Winter 2018 CISC101 11/29/2018 CISC101 Reminders
CISC101 Reminders Assn 3 due Friday, this week. Quiz 3 next week.
Exceptions and files Taken from notes by Dr. Neil Moore
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
Winter 2018 CISC101 12/2/2018 CISC101 Reminders
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Winter 2018 CISC101 12/5/2018 CISC101 Reminders
CISC101 Reminders Quiz 1 grading underway Next Quiz, next week.
CISC101 Reminders Quiz 2 this week.
Fall 2018 CISC124 2/15/2019 CISC124 TA names and s will be added to the course web site by the end of the week. Labs start next week in JEFF 155:
Winter 2019 CISC101 2/17/2019 CISC101 Reminders
CISC124 Labs start this week in JEFF 155. Fall 2018
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
CISC101 Reminders All assignments are now posted.
15-110: Principles of Computing
CISC101 Reminders Labs start this week. Meet your TA! Get help with:
Winter 2019 CMPE212 4/7/2019 CMPE212 – Reminders
CISC101 Reminders Assignment 2 due today.
Winter 2019 CISC101 4/16/2019 CISC101 Reminders
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
CMPE212 – Reminders Course Web Site:
Introduction to Computer Science
CISC101 Reminders Quiz 1 marking underway.
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
CISC101 Reminders All assignments are now posted.
Winter 2019 CISC101 4/28/2019 CISC101 Reminders
Winter 2019 CISC101 5/17/2019 CISC101 Reminders
Winter 2019 CMPE212 5/25/2019 CMPE212 – Reminders
Winter 2019 CISC101 5/26/2019 CISC101 Reminders
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
Winter 2019 CISC101 5/30/2019 CISC101 Reminders
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 Emails 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

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

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

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

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

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

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

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

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

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 (6553510, 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