Lecture #12: Quick: Exceptions and SQL

Similar documents
Exceptions & a Taste of Declarative Programming in SQL

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

Pairs and Lists. (cons 1 2) 1 2. (cons 2 nil) 2 nil. Not a well-formed list! 1 > (cdr x) 2 > (cons 1 (cons 2 (cons 3 (cons 4 nil)))) ( ) (Demo)

61A Lecture 25. Friday, October 28

Declarative Programming

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013

CIS192 Python Programming

CIS192 Python Programming

CIS192 Python Programming

CIS192 Python Programming

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

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

Review 3. Exceptions and Try-Except Blocks

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses

CS 11 python track: lecture 2

Exceptions CS GMU

CS Programming Languages: Python

Object Oriented Programming

Computational Concepts Toolbox. Object Oriented Programming. Today: class. Review: Objects

Lecture 18. Classes and Types

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

Lecture 21. Programming with Subclasses

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Lecture 7: Lambda & Abstract Data Types

EXCEPTIONS, CALCULATOR 10

INTERPRETERS AND TAIL CALLS 9

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Exception Handling. Genome 559

Class extension and. Exception handling. Genome 559

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Lecture #2: Programming Structures: Loops and Functions

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

Exception Handling and Debugging

LECTURE 4 Python Basics Part 3

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

COMP 204: Sets, Commenting & Exceptions

Lecture #3: Recursion

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

CS Lecture 26: Grab Bag. Announcements

Python File Modes. Mode Description. Open a file for reading. (default)

Python. Tutorial Lecture for EE562 Artificial Intelligence for Engineers

CSE : Python Programming

MUTABLE LISTS AND DICTIONARIES 4

Exceptions and File I/O

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

CS11 Advanced C++ Fall Lecture 3

CS 11 python track: lecture 3. n Today: Useful coding idioms

Class extension and. Exception handling. Genome 559

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

CS108 Lecture 19: The Python DBAPI

SCHEME AND CALCULATOR 5b

Lecture #3: Recursion

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

TUPLES AND RECURSIVE LISTS 5

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Collections. Lists, Tuples, Sets, Dictionaries

Final Exam Version A

Exceptions in Python. AMath 483/583 Lecture 27 May 27, Exceptions in Python. Exceptions in Python

CS 3 Introduction to Software Engineering. 3: Exceptions

6.001 Notes: Section 4.1

Exception Safe Coding

Exceptions & error handling in Python 2 and Python 3

Exceptions in Java

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

1 Lecture 6: Conditionals and Exceptions

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

CSc 120. Introduction to Computer Programming II. 07: Excep*ons. Adapted from slides by Dr. Saumya Debray

CS 11 python track: lecture 4

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1

Programming Languages: Application and Interpretation

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

Python for Astronomers. Errors and Exceptions

Abstract Data Types. David E. Culler CS8 Computational Structures in Data Science Lecture 7 March 7, 2016

At full speed with Python

CS61A Lecture 20 Object Oriented Programming: Implementation. Jom Magrotker UC Berkeley EECS July 23, 2012

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

Structure and Flow. CS 3270 Chapter 5

Search. The Nearest Neighbor Problem

Laboratorio di Tecnologie dell'informazione

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

New York University School of Continuing and Professional Studies Management and Information Technology. Advanced Python. Homework, Session 5

Object Oriented Programming

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

Outline. Announcements. Homework 2. Boolean expressions 10/12/2007. Announcements Homework 2 questions. Boolean expression

Programming Languages: Application and Interpretation

pygtrie Release Jul 03, 2017

CS 61B Discussion 5: Inheritance II Fall 2014

MEMOIZATION, RECURSIVE DATA, AND SETS

MEIN 50010: Python Flow Control

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Python for Informatics

COMP 204: Sets, Commenting & Exceptions

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

Programming in Python 3

Transcription:

UC Berkeley EECS Adj. Assistant Prof. Dr. Gerald Friedland Computational Structures in Data Science Lecture #12: Quick: Exceptions and SQL Administrivia Open Project: Starts Monday! Creative data task Similar to data8, except you write the code Lab Monday: SQL Lab Monday next week: Talk about Project Homework: Extra days due to Thanksgiving Lectures: This one, one more, and Q&A during RRR week April 6th, 2018 http://inst.eecs.berkeley.edu/~cs88 2 Computational Concepts Toolbox Today: Exceptions (read 4.3) Data type: values, literals, operations, Expressions, Call expression Variables Assignment Statement Sequences: tuple, list Dictionaries Data structures Tuple assignment Function Definition Statement Conditional Statement Iteration: list comp, for, while Lambda function expr. Higher Order Functions as Values, Args, Results Higher order function patterns Map, Filter, Reduce Function factories Recursion Linear, Tail, Tree Abstract Data Types Mutation Iterators and Generators Object Oriented Programming Classes Exceptions Declarative Programming Mechanism in a programming language to declare and respond to exceptional conditions enable non-local continuations of control Often used to handle error conditions Unhandled exceptions will cause python to halt and print a stack trace You already saw a non-error exception end of iterator Exceptions can be handled by the program instead try, except, raise statements Exceptions are objects! They have classes with constructors 3 4

Handling Errors Function receives arguments of improper type? Resource, e.g., file, is not available Network connection is lost or times out? Example exceptions >>> 3/0 ZeroDivisionError: division by zero >>> str.lower(1) TypeError: descriptor 'lower' requires a 'str' object but received a 'int' >>> ""[2] IndexError: string index out of range >>> Unhandled, thrown back to the top level interpreter Or halt the Python program 5 6 Functions Exceptional exit from functions Q: What is a function supposed to do? A: One thing well Q: What should it do when it is passed arguments that don t make sense? >>> def divides(x, y):... return y%x == 0... >>> divides(0, 5)??? >>> def get(data, selector):... return data[selector]... >>> get({'a': 34, 'cat':'9 lives'}, 'dog )???? >>> def divides(x, y):... return y%x == 0... >>> divides(0, 5) File "<stdin>", line 2, in divides ZeroDivisionError: integer division or modulo by zero >>> def get(data, selector):... return data[selector]... >>> get({'a': 34, 'cat':'9 lives'}, 'dog') File "<stdin>", line 2, in get KeyError: 'dog' >>> Function doesn t return but instead execution is thrown out of the function 7 8

Continue out of multiple calls deep Types of exceptions TypeError -- A function was passed the wrong number/type of argument NameError -- A name wasn't found KeyError -- A key wasn't found in a dictionary RuntimeError -- Catch-all for troubles during interpretation... Recursion/Stack unwinds until exception is handled or top 9 10 Flow of control stops at the exception Assert Statements And is thrown back to wherever it is caught Allow you to make assertions about assumptions that your code relies on Use them liberally! Incoming data is dirty till you ve washed it assert <assertion expression>, <string for failed> Raise an exception of type AssertionError Ignored in optimize flag: python3 O Governed by bool debug def divides(x, y): assert x!= 0, Denominator must be non-zero return y%x == 0 11 12

Handling Errors try / except Raise statement Wrap your code in try except statements Exception are raised with a raise statement try: <try suite> except <exception class> as <name>: <except suite>... # continue here if <try suite> succeeds w/o exception Execution rule <try suite> is executed first If during this an exception is raised and not handled otherwise And if the exception inherits from <exception class> Then <except suite> is executed with <name> bound to the exception raise <exception> <expression> must evaluate to a subclass of BaseException or an instance of one Exceptions are constructed like any other object TypeError( Bad argument ) Control jumps to the except suite of the most recent try that handles the exception 13 14 Exceptions are Classes class NoiseyException(Exception): def init (self, stuff): print("bad stuff happened", stuff) Part II Intro to Declarative Programming SQL try: return fun(x) except: raise NoiseyException((fun, x)) 15 16

Data 8 Tables ordered collection of labeled columns of anything dict, record,tuple label values T[ label ] select, where, take, drop, group stats, bin sample pivot, pivot_bin split join Numpy array A single, simple, powerful data structure for all Inspired by Excel, SQL, R, Pandas, Numpy, Database Management Systems DBMS are persistent tables with powerful relational operators Important, heavily used, interesting! A table is a collection of records, which are rows that have a value for each column row has a value for each column Name Latitude Longitude Berkeley 38 122 Cambridge 42 71 Minneapolis 45 93 column has a name and a type table has columns and rows Structure Query Language (SQL) is a declarative programming language describing operations on tables 3/29/16 DSed @ UCB 17 18 SQL SQL example A declarative language Described what to compute Imperative languages, like python, describe how to compute it Query processor (interpreter) chooses which of many equivalent query plans to execute to perform the SQL statements ANSI and ISO standard, but many variants select statement creates a new table, either from scratch or by projecting a table create table statement gives a global name to a table Lots of other statements analyze, delete, explain, insert, replace, update, The action is in select SQL statements create tables Give it a try with sqlite3 or http://kripken.github.io/sql.js/gui/ Each statement ends with ; culler$ sqlite3 SQLite version 3.9.2 2015-11-02 18:31:45 Enter ".help" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persistent database. sqlite> select 38 as latitude, 122 as longitude, "Berkeley" as name; 38 122 Berkeley sqlite> 19 20

select Comma-separated list of column descriptions Column description is an expression, optionally followed by as and a column name select [expression] as [name], [expression] as [name];... SQL: creating a named table select 45, 93, "Minneapolis ; Selecting literals creates a one-row table union of select statements is a table containing the union of the rows cities: Latitude Longitude Name 38 122 Berkeley 42 71 Cambridge 45 93 Minneapolis Latitude Longitude Name 38 122 Berkeley 42 71 Cambridge 45 93 Minneapolis 21 22 create table SQL: using named tables - from SQL often used interactively Result of select displayed to the user, but not stored Create table statement gives the result a name Like a variable, but for a permanent object create table [name] as [select statement]; select "west coast" as region, name from cities where longitude >= 115 union select "other", name from cities where longitude < 115 Region west coast other other Name Berkeley Cambridge Minneapolis cities: Latitude Longitude Name 38 122 Berkeley 42 71 Cambridge 45 93 Minneapolis 23 24

Projecting existing tables Input table specified by from clause Subset of rows selected using a where clause Ordering of the selected rows declared using an order by clause select [columns] from [table] where [condition] order by [order] ; select * from cities where longitude > 115 order by name; Joining tables Two tables are joined by a comma to yield all combinations of a row from each create table climates as select "Berkeley" as city, "warm" as climate union select "Cambridge" as city, "cold" as climate; select * from cities, climates Name Latitude Longitude Cambridge 42 71 Minneapolis 45 93 25 26 Join / Where Aggregation and grouping create table climates as select "Berkeley" as city, "warm" as climate union select "Cambridge" as city, "cold" as climate; select name, climate, latitude, longitude from cities, climates where name = city; Reduction operators can be applied over groupings of rows create table climates as select "Berkeley" as city, "warm" as climate union select "Cambridge" as city, "cold" as climate union select "Minneapolis" as city, "cold" as climate; select climate, min(latitude) from cities, climates where name = city group by climate; 27 28

Summary Exceptions provide a way to handle unexpected cases and errors Transfers control to enclosing handler of matching type assert, raise <expression>, try: except <type> as <name> SQL a declarative programming language on relational tables largely familiar to you from data8 create, select, where, order, group by, join More in lab! 29