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

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]

Exceptions & a Taste of Declarative Programming in SQL

Lecture #12: Quick: Exceptions and SQL

Computer Science 9608 (Notes) Chapter: 4.3 Further programming

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

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

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

Python Tutorial. Day 2

Introduction to python

STSCI Python Introduction. Class URL

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

CSC148 Fall 2017 Ramp Up Session Reference

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

CS Programming Languages: Python

Object Oriented Programming

A Little Python Part 3

ECE 122. Engineering Problem Solving with Java

Exceptions & error handling in Python 2 and Python 3

Exceptions CS GMU

Control Structures 1 / 17

Class extension and. Exception handling. Genome 559

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

CS 11 python track: lecture 2

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

Object Oriented Programming

A Little Python Part 3

Chapter 9: Dealing with Errors

Exception Handling and Debugging

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

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

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

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

CS 11 python track: lecture 4

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

Review 3. Exceptions and Try-Except Blocks

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

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

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

Advanced Python. Executive Summary, Session 1

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

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

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

Introduction to Computer Programming for Non-Majors

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

Introduction to Python programming, II

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

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

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

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

CIS192: Python Programming

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

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

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

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

Modules and scoping rules

Python debugging and beautification

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

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

MEIN 50010: Python Flow Control

Programming with Python

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

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

#11: File manipulation Reading: Chapter 7

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

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

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

Transcription:

CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26

Outline 1 Iterators, Generators, Exceptions, and IO Iterators Generators Exceptions Input Output Context Managers Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 2 / 26

What s a For Loop? What s going on here: for num in [1, 2, 3]: print num Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 4 / 26

Iterators Iterators in action: >>> i = iter(l) >>> next(i) 1 >>> next(i) 2 >>> next(i) 3 >>> next(i) StopIteration Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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} Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 9 / 26

Infinite Generators Infinite computations... itertools.count() is an infinite generator itertools.islice() lets you slice iterables Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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) Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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. Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 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 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 26 / 26