CIS192 Python Programming

Similar documents
CIS192 Python Programming

CIS192 Python Programming

CIS192 Python Programming

FILE HANDLING AND EXCEPTIONS

LECTURE 4 Python Basics Part 3

Iterators & Generators

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Exceptions & a Taste of Declarative Programming in SQL

Lecture #12: Quick: Exceptions and SQL

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

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

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

4.3 FURTHER PROGRAMMING

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

Computer Science 9608 (Notes) Chapter: 4.3 Further programming

Python Tutorial. Day 2

Introduction to python

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

Object Oriented Programming

ECE 122. Engineering Problem Solving with Java

STSCI Python Introduction. Class URL

CS Programming Languages: Python

A Little Python Part 3

CSC148 Fall 2017 Ramp Up Session Reference

CS 11 python track: lecture 2

CIS192: Python Programming

file_object=open( file_name.txt, mode ) f=open( sample.txt, w ) How to create a file:

Object Oriented Programming

ECE 364 Software Engineering Tools Lab. Lecture 8 Python: Advanced I

A Little Python Part 3

Exceptions & error handling in Python 2 and Python 3

Exceptions CS GMU

Control Structures 1 / 17

Class extension and. Exception handling. Genome 559

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

CS 11 python track: lecture 4

Chapter 9: Dealing with Errors

Review 3. Exceptions and Try-Except Blocks

Exception Handling and Debugging

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Question 1. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop())

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Exception Handling. Genome 559

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function

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

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

Class extension and. Exception handling. Genome 559

Python for Astronomers. Errors and Exceptions

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

CS159. Nathan Sprague

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

CS 115 Lecture 4. More Python; testing software. Neil Moore

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

CIS192 Python Programming

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

List Comprehensions. Function Definitions. This is the same as mapping the doubling function on the list [1,2,3], but without an explicit

Advanced Python. Executive Summary, Session 1

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

F21SC Industrial Programming: Python: Classes and Exceptions

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

Introduction to Python programming, II

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

Idioms and Anti-Idioms in Python

Exceptions and File I/O

Delayed Expressions Fall 2017 Discussion 9: November 8, Iterables and Iterators. For Loops. Other Iterable Uses

Try and Error. Python debugging and beautification

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

Introduction to Computer Programming for Non-Majors

Introduction to Python programming, II

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Slide Set 15 (Complete)

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

Introduction to Computer Programming for Non-Majors

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

Structure and Flow. CS 3270 Chapter 5

Programming with Python

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

#11: File manipulation Reading: Chapter 7

CS Lecture 26: Grab Bag. Announcements

MUTABLE LISTS AND DICTIONARIES 4

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

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Question 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

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

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

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

CIS192 Python Programming

Modules and scoping rules

CIS192 Python Programming

Python debugging and beautification

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

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1

CS 115 Data Types and Arithmetic; Testing. Taken from notes by Dr. Neil Moore

1 Getting Started 2. 2 Conditionals, Loops Conditionals Loops... 4

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Transcription:

CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26

Outline 1 Iterators, Generators, Exceptions, and IO Iterators Generators Exceptions Input Output Context Managers Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 2 / 26

What s a For Loop? What s going on here: for num in [1, 2, 3]: print num Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 3 / 26

Iterables An iterable can be for-looped over, and is: an object that supports iter returns iterator or getitem for indexed lookup e.g. string, list, tuple, file Wait, what s an iterator? returns the next item from calls to next () raises StopIteration if next () called too many times Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 4 / 26

Iterators Iterators in action: >>> i = iter(l) >>> next(i) 1 >>> next(i) 2 >>> next(i) 3 >>> next(i) StopIteration Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 5 / 26

Iterators for... in... is just syntactic sugar for the following: 1 Call iter(...) to create an iterator 2 Call next on the iterator 3 Catch StopIteration exceptions Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 6 / 26

Generators A generator is a function that behaves like an iterable, but without all the extra boilerplate and extra state next(generator) will execute the function body until yield is reached yield is like return, except that the state is remembered Reaching the end of the function raises StopIteration Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 7 / 26

Generator Comprehensions (x ** 2 for x in [1, 2, 3])#Not a tuple comprehension! A generator comprehension creates a generator object g = ({expr} for x in iterable) is equivalent to: def g(): for x in iterable: yield {expr} Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 8 / 26

Why Generators? Memory Efficient Keep 1 value in memory at a time The function state is minimal in terms of memory Use a generator over a list whenever you iterate Great: for square in (x ** 2 for x in range(10000)) Not so great: for square in [x ** 2 for x in range(10000)] Good for aggregating (summing, counting) items Good for infinite sequences Bad if you need to inspect the individual values Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 9 / 26

Infinite Generators Infinite computations... itertools.count() is an infinite generator itertools.islice() lets you slice iterables Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 10 / 26

Raise Exceptions An exception can be raised with the raise keyword Raising an exception sends control back up to the nearest enclosing exception handler What if the exception isn t handled? The interpreter prints a stack trace The program exits or returns to the interactive loop Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 11 / 26

Exceptions KeyError: accessing a non-existent dictionary key AttributeError: calling a non-existent method NameError: referencing a non-existent variable TypeError: mixing data-types ValueError: right type, wrong value ImportError: module not available IOError: file does not exist Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 12 / 26

Exceptions Syntax: Java: try...catch to handle, and throw to generate Python: try...except to handle, and raise to generate When do I use try...except? Opening a file (may not exist) User input (never trust anybody) Connecting to a database (might be unavailable) Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 13 / 26

Catching Exceptions Catch all exceptions, regardless of type: def int_default_0(x): try: return int(x) except: return 0 >>> int_default_0( 5 ) 5 >>> int_default_0( hi ) 0 # would have thrown a ValueError >>> int_default_0([]) 0 # would have thrown a TypeError Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 14 / 26

Catching Exceptions Catch only a specific type: def int_default_0(x): try: return int(x) except ValueError: return 0 >>> int_default_0( hi ) 0 >>> int_default_0([]) TypeError Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 15 / 26

Catching Exceptions Catch multiple types together: def int_default_0(x): try: return int(x) except (ValueError, TypeError): return 0 >>> int_default_0( hi ) 0 >>> int_default_0([]) 0 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 16 / 26

Catching Exceptions Multiple except blocks: def int_default_0(x): try: return int(x) except ValueError: print "Caught a ValueError." except TypeError: print "Caught a TypeError." >>> int_default_0( hi ) Caught a ValueError. >>> int_default_0([]) Caught a TypeError. Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 17 / 26

Catching Exceptions Get a reference to the Exception class instance: def int_default_0(x): try: return int(x) except (ValueError, TypeError) as e: print(e) return 0 >>> int_default_0( hi ) invalid literal for int() with base 10: hi >>> int_default_0([]) int() argument must be a string or a number, not list Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 18 / 26

Catching Exceptions Enclose code that might throw an exception in a try block Specify an except block to be executed if an exception is raised It s best to specify specific errors with except ExceptionType as name: Catch any type of error with except: Include an else block if you need to do something when there isn t an error The finally block gets executed no matter what You can have multiple except clauses There must be at least 1 except clause or a finally clause Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 19 / 26

User Defined Exceptions Often inheriting from Exception is enough class MyException(Exception) pass You can define other attributes Access those attributes when the exception is caught Implementing str and repr is also useful Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 20 / 26

Standard Input You can ask the user for input on STD_IN input() will read and return STD_IN up to a newline input(prompt) prints str(prompt) before reading input Standard In is accessible as a file-object: sys.stdin print(string) sends string to STD_OUT print(s, end= ) prints without a trailing newline Standard In is accessible as a file-object: sys.stdout Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 21 / 26

File IO open(name, mode) returns a file-object name is the path of the file to open If mode == r, the file is open in read-only mode If mode == w, the file is open in write-only mode w Truncates the file first If mode == a, like w but appends to the file Supplying + after one of rwa is for reading and writing Starting position in file depends on rwa w still truncates Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 22 / 26

File Operations Given a file object f = open(name, a+ ) f.readline() reads a line f.read() reads the whole file (up to EOF) f.write(string) writes string without adding a newline f.writelines(lines) writes lines without adding newlines f.flush() flushes the write buffers f.close() flushes and closes the file f.seek(offset) sets the position in the file Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 23 / 26

With Statement with expr as name: begins a managed block Before the block is executed: The enter () method of expr is called The result is assigned to name The block is executed in a try block Any exceptions are passed to the exit () method of expr exit (exc_type, exc_val, exc_trace_back) The arguments to exit can be used to handle certain errors finally exit (None, None, None) will be called Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 24 / 26

File With Statements It s good practice to always close files Remembering is hard... with open(...)as f_name: The enter and exit methods of file-objects make sure that the file gets closed Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 25 / 26

Take-aways Use a Generator if you don t need to have it all at once If something can fail use a try block with statements can manage resources for you Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 26 / 26