Lecture 11. Asserts and Error Handling

Similar documents
Lecture 11. Asserts and Error Handling

Lecture 9. Memory and Call Stacks

CS Prelim 1 Review Fall 2012

Review 3. Exceptions and Try-Except Blocks

PREPARING FOR PRELIM 1

CS Prelim 2 Review Fall 2017

Lecture 18. Classes and Types

Lecture 21. Programming with Subclasses

CS Prelim 2 Review Fall 2012

Lecture 12. Lists (& Sequences)

CS Prelim 2 Review Fall 2015

CS Prelim 2 Review Fall 2014

CS Prelim 1 Review Fall 2018

CS 1110 Final, December 8th, Question Points Score Total: 100

CS 1110 Prelim 1 October 17th, 2013

CS1110. Lecture 1: Final review session. Review materials See website for a version of last year s final with conventions redone to match this year.

CS 1110 Final, December 8th, Question Points Score Total: 100

CS Prelim 1 Review Fall 2013

CS Prelim 1 Review Fall 2017

CS Lecture 26: Grab Bag. Announcements

Lecture 21. Programming with Subclasses

CS 1110 Prelim 1 October 15th, 2015

CS 1110 Prelim 1 March 10, 2015

Lecture 21. Programming with Subclasses

CS1110 Lab 6 (Mar 17-18, 2015)

CS Prelim 1 Review Fall 2013

CS Lecture 19: Loop invariants

Lecture 19. Using Classes Effectively

CS Prelim 1 Review Fall 2016

Lecture 10. Memory in Python

CS 1110 Prelim 1 October 4th, 2012

CS Prelim 2 Review Fall 2018

Lecture 4. Defining Functions

PREPARING FOR PRELIM 2

PREPARING FOR THE FINAL EXAM

CS 1110 Prelim 2 November 14th, 2013

Announcements for This Lecture

Fundamentals of Programming (Python) Getting Started with Programming

CS 1110 Prelim 2 November 6th, 2012

Lecture 13. Call Stacks & Debugging

Iteration and For Loops

CS 1110 Final, December 17th, Question Points Score Total: 100

CS61A Lecture 9 Immutable Data Structures. Jom Magrotker UC Berkeley EECS July 2, 2012

Getting Started with Python

Lecture 18. Using Classes Effectively

Last Name: First: Netid: Section. CS 1110 Final, December 17th, 2014

Lecture 17: Classes (Chapter 15)

CS 1110, LAB 3: MODULES AND TESTING First Name: Last Name: NetID:

CSC148 Recipe for Designing Classes

Lecture 7. Memory in Python

a correct statement? You need to know what the statement is supposed to do.

Assertions, pre/postconditions

Lecture 9: Memory in Python

Lecture 19. Operators and Abstraction

PREPARING FOR THE FINAL EXAM

Lecture 24. GUI Applications

Outline. software testing: search bugs black-box and white-box testing static and dynamic testing

Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute.

Announcements for this Lecture

Lecture 6: Specifications & Testing

Lecture 22. While Loops

Functions with Parameters and Return Values

CS 1110: Introduction to Computing Using Python Loop Invariants

Errors. And How to Handle Them

Lecture 13. For-Loops

CISC 110 Week 1. An Introduction to Computer Graphics and Scripting

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

CSC Java Programming, Fall Java Data Types and Control Constructs

Lecture 18: Using Classes Effectively (Chapter 16)

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

Lecture 5. Defining Functions

This guide helps you understand how operations available on the printer can be used to adjust and customize color output.

CS1110 Lab 5: Practice for A4 (Mar 8-9, 2016) First Name: Last Name: NetID:

CS 1110 Prelim 1 October 12th, 2017

Lecture 15. More Recursion

Control Structures 1 / 17

Conditionals & Control Flow

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

ECSE 321 Assignment 2

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Announcements for This Lecture

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Exceptions & a Taste of Declarative Programming in SQL

CISC 1115 (Science Section) Brooklyn College Professor Langsam. Assignment #5

mith College Computer Science CSC103 How Computers Work Week 7 Fall 2017 Dominique Thiébaut

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

Graphics Overview ECE2893. Lecture 19. ECE2893 Graphics Overview Spring / 15

Structure and Flow. CS 3270 Chapter 5

CS 1110 Final, December 16th, 2013

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

CS Lecture 18: Card Tricks. Announcements. Slides by D. Gries, L. Lee, S. Marschner, W. White

CS 1110 Prelim 1 March 15th, 2016

Readings for This Lecture

Text Input and Conditionals

Lecture 14. Nested Lists and Dictionaries

CS 100: Computability, Python Lists

Python for Informatics

Announcements for the Class

Transcription:

Lecture 11 Asserts and Error Handling

Announcements for Today Reading Reread Chapter 3 10.0-10.2, 10.4-10.6 for Thu Prelim, Oct 13 th 7:30-9:00 Material up October 4th Study guide next week Conflict with Prelim time? Submit to Prelim 1 Conflict assignment on CMS Do not submit if no conflict Assignments Assignment 1 now complete Unless we gave extension Assignment 2 in progress Ready for pick-up Thurs Solutions posted in CMS Assignment 3 due next week Before you leave for break Same length as A1 Get help now if you need it 9/27/16 Asserts & Error Handling 2

Using Color Objects in A3 New classes in colormodel RGB, CMYK, and HSV Each has its own attributes RGB: red, blue, green CMYK: cyan, magenta, yellow, black HSV: hue, saturation, value Attributes have invariants Limits the attribute values Example: red is int in 0..255 Get an error if you violate c r id1 128 >>> import colormodel >>> c = colormodel.rgb(128,0,0) >>> r = c.red id1 red 128 green 0 blue 0 RGB >>> c.red = 500 # out of range AssertionError: 500 outside [0,255] 9/27/16 Asserts & Error Handling 3

Using Color Objects in A3 New classes in colormodel RGB, CMYK, and HSV Each has its own attributes RGB: red, blue, green CMYK: cyan, magenta, yellow, black HSV: hue, saturation, value Attributes have invariants Limits the attribute values Example: red is int in 0..255 Get an error if you violate c r id1 128 >>> import colormodel >>> c = colormodel.rgb(128,0,0) >>> r = c.red id1 red 128 green 0 RGB Constructor function. To make blue a new color. 0 >>> c.red = 500 # out Accessing of range AssertionError: 500 outside Attribute [0,255] 9/27/16 Asserts & Error Handling 4

How to Do the Conversion Functions def rgb_to_cmyk(rgb): """Returns: color rgb in space CMYK Precondition: rgb is an RGB object""" # DO NOT CONSTRUCT AN RGB OBJECT # Variable rgb already has RGB object # 1. Access attributes from rgb folder # 2. Plug into formula provided # 3. Compute the new cyan, magenta, etc. values # 4. Construct a new CMYK object # 5. Return the newly constructed object Only time you will ever call a constructor 9/27/16 Asserts & Error Handling 5

Recall: The Call Stack Functions are stacked Cannot remove one above w/o removing one below Sometimes draw bottom up (better fits the metaphor) Stack represents memory as a high water mark Must have enough to keep the entire stack in memory Error if cannot hold stack Frame 1 Frame 2 Frame 3 Frame 4 Frame 6 calls calls calls calls 9/27/16 Asserts & Error Handling 6

Errors and the Call Stack # error.py def function_1(x,y): return function_2(x,y) def function_2(x,y): return function_3(x,y) def function_3(x,y): calls calls return x/y # crash here calls if name == ' main ': print function_1(1,0) 9/27/16 Asserts & Error Handling 7

Errors and the Call Stack # error.py def function_1(x,y): return function_2(x,y) def function_2(x,y): return function_3(x,y) def function_3(x,y): return x/y # crash here if name == ' main ': print function_1(1,0) Crashes produce the call stack: Traceback (most recent call last): File "error.py", line 20, in <module> print function_1(1,0) File "error.py", line 8, in function_1 return function_2(x,y) File "error.py", line 12, in function_2 return function_3(x,y) File "error.py", line 16, in function_3 return x/y Make sure you can see line numbers in Komodo. Preferences è Editor 9/27/16 Asserts & Error Handling 8

Errors and the Call Stack # error.py Script code. Global space def function_1(x,y): return function_2(x,y) def function_2(x,y): return function_3(x,y) def function_3(x,y): return x/y # crash here Where error occurred (or print where function_1(1,0) was found) if name == ' main ': Crashes produce the call stack: Traceback (most recent call last): File "error.py", line 20, in <module> print function_1(1,0) File "error.py", line 8, in function_1 return function_2(x,y) File "error.py", line 12, in function_2 return function_3(x,y) File "error.py", line 16, in function_3 return x/y Make sure you can see line numbers in Komodo. Preferences è Editor 9/27/16 Asserts & Error Handling 9

Assert Statements assert <boolean> assert <boolean>, <string> # Creates error if <boolean> false # As above, but displays <String> Way to force an error Why would you do this? Enforce preconditions! Put precondition as assert. If violate precondition, the program crashes Provided code in A3 uses asserts heavily def exchange(from_c, to_c, amt) """Returns: amt from exchange Precondition: amt is a float """ assert type(amt) == float Will do yourself in A4. 9/27/16 Asserts & Error Handling 10

Example: Anglicizing an Integer def anglicize(n): """Returns: the anglicization of int n. Precondition: n an int, 0 < n < 1,000,000""" assert type(n) == int, str(n)+' is not an int' assert 0 < n and n < 1000000, str(n)+' is out of range' # Implement method here 9/27/16 Asserts & Error Handling 11

Example: Anglicizing an Integer def anglicize(n): """Returns: the anglicization of int n. Precondition: n an int, 0 < n < 1,000,000""" assert type(n) == int, str(n)+' is not an int' assert 0 < n and n < 1000000, str(n)+' is out of range' # Implement method here Check (part of) the precondition Error message when violated 9/27/16 Asserts & Error Handling 12

Enforcing Preconditions is Tricky! def lookup_netid(nid): """Returns: name of student with netid nid. Precondition: nid is a string, which consists of 2 or 3 letters and a number""" assert????? Assert use expressions only. Cannot use if-statements. Each one must fit on one line. Sometimes we will only enforce part of the precondition 9/27/16 Asserts & Error Handling 13

Enforcing Preconditions is Tricky! def lookup_netid(nid): """Returns: name of student with netid nid. Precondition: nid is a string, which consists of 2 or 3 letters and a number""" assert type(nid) == str, str(nid) + ' is not a string' assert nid.isalnum(), nid+' is not just letters/digits' Returns True if s contains only letters, numbers. Does this catch all violations? 9/27/16 Asserts & Error Handling 14

Using Function to Enforce Preconditions def exchange(curr_from, curr_to, amt_from): """Returns: amount of curr_to received. Precondition: curr_from is a valid currency code Precondition: curr_to is a valid currency code Precondition: amt_from is a float""" assert??????, str(curr_from) + ' not valid' assert??????, str(curr_from) + ' not valid' assert type(amt_from)==float, str(amt_from) + ' not a float' 9/27/16 Asserts & Error Handling 15

Using Function to Enforce Preconditions def exchange(curr_from, curr_to, amt_from): """Returns: amount of curr_to received. Precondition: curr_from is a valid currency code Precondition: curr_to is a valid currency code Precondition: amt_from is a float""" assert iscurrency(curr_from), str(curr_from) + ' not valid' assert iscurrency(curr_to), str(curr_to) + ' not valid' assert type(amt_from)==float, str(amt_from) + ' not a float' 9/27/16 Asserts & Error Handling 16

Recovering from Errors try-except blocks allow us to recover from errors Do the code that is in the try-block Once an error occurs, jump to the catch Example: input = raw_input() # get number from user x = float(input) # convert string to float print 'The next number is '+str(x+1) print 'Hey! That is not a number!' might have an error executes if error happens 9/27/16 Asserts & Error Handling 17

Recovering from Errors try-except blocks allow us to recover Similar from to if-else errors Do the code that is in the try-block But always does try Once an error occurs, jump to the catch Just might not do all of the try block Example: input = raw_input() # get number from user x = float(input) # convert string to float print 'The next number is '+str(x+1) print 'Hey! That is not a number!' might have an error executes if error happens 9/27/16 Asserts & Error Handling 18

Try-Except is Very Versatile def isfloat(s): """Returns: True if string s represents a float""" x = float(s) return True return False Conversion to a float might fail If attempt succeeds, string s is a float Otherwise, it is not 9/27/16 Asserts & Error Handling 19

Try-Except and the Call Stack # recover.py def function_1(x,y): return function_2(x,y) return float('inf') Error pops frames off stack Starts from the stack bottom Continues until it sees that current line is in a try-block Jumps to except, and then proceeds as if no error def function_2(x,y): return function_3(x,y) line in a try function_1 function_2 pops def function_3(x,y): return x/y # crash here function_3 pops 9/27/16 Asserts & Error Handling 20

# recover.py def function_1(x,y): Try-Except and the Call Stack return function_2(x,y) return float('inf') def function_2(x,y): return function_3(x,y) def function_3(x,y): return x/y # crash here Error pops frames off stack How to return Starts from the stack bottom as a float. Continues until it sees that current line is in a try-block Jumps to except, and then proceeds as if no error Example: >>> print function_1(1,0) inf >>> No traceback! 9/27/16 Asserts & Error Handling 21

Tracing Control Flow def first(x): print 'Starting first.' second(x) print 'Caught at first print 'Ending first def third(x): print 'Starting third.' assert x < 1 print Ending third.' What is the output of first(2)? def second(x): print 'Starting second.' third(x) print 'Caught at second print 'Ending second 9/27/16 Asserts & Error Handling 22

Tracing Control Flow def first(x): print 'Starting first.' second(x) print 'Caught at first print 'Ending first def third(x): print 'Starting third.' assert x < 1 print Ending third.' What is the output of first(2)? def second(x): print 'Starting second.' third(x) print 'Caught at second print 'Ending second 'Starting first.' 'Starting second.' 'Starting third.' 'Caught at second' 'Ending second' 'Ending first' 9/27/16 Asserts & Error Handling 23

Tracing Control Flow def first(x): print 'Starting first.' second(x) print 'Caught at first print 'Ending first def third(x): print 'Starting third.' assert x < 1 print Ending third.' What is the output of first(0)? def second(x): print 'Starting second.' third(x) print 'Caught at second print 'Ending second 9/27/16 Asserts & Error Handling 24

Tracing Control Flow def first(x): print 'Starting first.' second(x) print 'Caught at first print 'Ending first def third(x): print 'Starting third.' assert x < 1 print Ending third.' What is the output of first(0)? def second(x): print 'Starting second.' third(x) print 'Caught at second print 'Ending second 'Starting first.' 'Starting second.' 'Starting third.' 'Ending third' 'Ending second' 'Ending first' 9/27/16 Asserts & Error Handling 25