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

Size: px
Start display at page:

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

Transcription

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

2 EXERCISE Type in the following code: def foo(): n = int(input("enter a number:")) print("n = ", n) print("reciprocal = ", str(1/n)) Run the code Call foo() and enter a number 2

3 Errors and exceptions in Python A Python program can have two kinds of errors:* Syntax errors: the code is not legal Python syntax detected before the program is run Excep*ons: the code is legal Python syntax but something goes wrong when the program is run An excep%on is an error that is only detected at run *me. * This does not count logic errors, which the Python system cannot detect 3

4 Some common exceptions FileNotFoundError file name or directory cannot be found IndexError an index into a string or list is out of bounds KeyError a non-existent key used to access a dic*onary TypeError arguments to an opera*on are of the wrong type ValueError type is OK but the value is not. E.g.: int("abc") 4

5 Handling exceptions try raise catch excep*on may occur excep*on occurs catch and handle the excep*on 5

6 Handling exceptions Example: try: code that might raise an excep%on except: code to handle the excep%on 6

7 Handling exceptions Example: try: infile = open(filename) except: print("could not open file: " + filename) 7

8 Handling exceptions Example: >>> f = open("no]here.txt") Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> f = open("no]here.txt") FileNotFoundError: [Errno 2] No such file or directory: 'no]here.txt' >>> >>> try: f = open("no]here.txt") except: print("error: file not found") Error: file not found >>> 8

9 EXERCISE Add try and except statements to handle an excep*on that may occur. def foo(): n = int(input("enter a number:")) print("n = ", n) print("reciprocal = ", str(1/n)) try: code that might raise an excep%on except: code to handle the excep%on 9

10 EXERCISE-sol Run the code and enter a non-digit value. What's the problem? def foo(): try: n = int(input("enter a number:")) print("n = ", n) print("reciprocal = ", str(1/n)) except: print("divide-by-zero error") 10

11 Handling exceptions Example: try: This will catch any excep*on raised in the try block This may not always be desirable code that might raise an excep%on except: code to handle the excep%on 11

12 Handling exceptions 12

13 Handling exceptions 13

14 Handling exceptions 14

15 Handling exceptions CULPRIT: Catching all excep%ons (BAD STYLE) The file was read! The error message doesn't make sense 15

16 Handling exceptions Deals with a specific excep%on Does not mislead on other excep%ons 16

17 EXERCISE Modify your code to catch a ZeroDivisionError. def foo(): try: n = int(input("enter a number:")) print("n = ", n) print("reciprocal = ", str(1/n)) except: print("error: Divide-by-zero error") 17

18 Handling multiple exceptions 1 Handle mul%ple excep%ons in the same way Behavior for both excep%ons is the same 18

19 Handling multiple exceptions 2 Handle mul%ple excep%ons in different ways 19

20 Handling multiple exceptions 2 20

21 Exception propagation an unhandled excep*on is passed along from a func*on to its caller un*l (a) it is handled; or (b) it reaches the top level of execu*on 21

22 EXERCISE Download: h]p://www2.cs.arizona.edu/classes/cs120/fall18/notes/propagate.py def fun1(x): return 1/x def fun2(x): return 1 + fun1(x) def main(): z = fun2(3) print(z) z = fun2(0) print(z) main() Make 2 copies of the program. 1- Modify the code to catch the excep*on in fun2(). 22

23 EXERCISE-(cont.) In which func*on does the error occur? Which func*on catches the error? 23

24 def fun1(x): return 1/x EXERCISE Download: h]p://www2.cs.arizona.edu/classes/cs120/summer18/notes/propagate.py def fun2(x): return 1 + fun1(x) def main(): z = fun2(3) print(z) z = fun2(0) print(z) main() 2- Modify the code to catch the excep*on in main(). 24

25 EXERCISE-(cont.) Call order: main() à calls fun2() à calls fun1() In which func*on does the error occur? Which func*on catches the error? The error occurs in fun1(). When it's not "handled" there, Python goes to the caller of fun1(), which is fun2(). If not handled there, Python goes to the caller of fun2(), which is main(). 25

26 Dealing with exceptions If possible and appropriate, try to recover from the excep*on depends on the problem spec, nature of the excep*on If recovery is not possible, exit the program import sys... sys.exit(1) exits the program with error code 1 (this indicates that an error occurred to any other program that may be using this program) 26

27 Example import sys def read_input(filename): try: fileobj = open(filename) except IOError: print( ERROR: could not open file + filename) sys.exit(1) for line in fileobj:...process contents of file... 27

28 Else clause (optional) Executed if no excep*ons are raised.... for fname in names_list: try: f = open(fname) except IOError: print("cannot open ", fname) else: print("length of", fname, "is", len(f.readlines())) f.close() 28

29 Exceptions: summary Avoid naked except if at all possible catch and handle specific excep*ons by name other excep*ons will propagate up to the caller Keep the try except separa*on as small as possible makes the code easier to understand avoids inadvertent masking of excep*ons Recover from the excep*on if possible; otherwise exit with error code 1 29

Introduction to python

Introduction to python Introduction to python 13 Files Rossano Venturini rossano.venturini@unipi.it File System A computer s file system consists of a tree-like structured organization of directories and files directory file

More information

Exceptions CS GMU

Exceptions CS GMU Exceptions CS 112 @ GMU Exceptions When an unrecoverable action takes place, normal control flow is abandoned: an exception value crashes outwards until caught. various types of exception values can be

More information

Exception Handling. Genome 559

Exception Handling. Genome 559 Exception Handling Genome 559 Review - classes Use your own classes to: - package together related data - conceptually organize your code - force a user to conform to your expectations Class constructor:

More information

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

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3] What is an Exception? Exception Handling BBM 101 - Introduction to Programming I Hacettepe University Fall 2016 Fuat Akal, Aykut Erdem, Erkut Erdem An exception is an abnormal condition (and thus rare)

More information

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

Python File Modes. Mode Description. Open a file for reading. (default) UNIT V FILES, MODULES, PACKAGES Files and exception: text files, reading and writing files, format operator; command line arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative

More information

CS 11 python track: lecture 2

CS 11 python track: lecture 2 CS 11 python track: lecture 2 Today: Odds and ends Introduction to object-oriented programming Exception handling Odds and ends List slice notation Multiline strings Docstrings List slices (1) a = [1,

More information

Introduction to: Computers & Programming: Exception Handling

Introduction to: Computers & Programming: Exception Handling Introduction to: Computers & Programming: Adam Meyers New York University Summary What kind of error raises an exception? Preventing errors How to raise an exception on purpose How to catch an exception

More information

Python for Astronomers. Errors and Exceptions

Python for Astronomers. Errors and Exceptions Python for Astronomers Errors and Exceptions Exercise Create a module textstat that contains the functions openfile(filename, readwrite=false): opens the specified file (readonly or readwrite) and returns

More information

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling COMP1730/COMP6730 Programming for Scientists Exceptions and exception handling Lecture outline * Errors * The exception mechanism in python * Causing exceptions (assert and raise) * Handling exceptions

More information

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

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,

More information

CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray

CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray 01-c: Python review 2 python review: lists strings 3 Strings lists names = "John, Paul, Megan, Bill, Mary" names

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class myclass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = myclass('student', 'teacher')

More information

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

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria CSE 399-004: Python Programming Lecture 5: Course project and Exceptions February 12, 2007 Announcements Still working on grading Homeworks 3 and 4 (and 2 ) Homework 5 will be out by tomorrow morning I

More information

Introduction to programming using Python

Introduction to programming using Python Introduction to programming using Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ Session 6-2 1 Objectives To open a file, read/write data from/to a file To use file dialogs

More information

Class extension and. Exception handling. Genome 559

Class extension and. Exception handling. Genome 559 Class extension and Exception handling Genome 559 Review - classes 1) Class constructors - class MyClass: def init (self, arg1, arg2): self.var1 = arg1 self.var2 = arg2 foo = MyClass('student', 'teacher')

More information

LECTURE 4 Python Basics Part 3

LECTURE 4 Python Basics Part 3 LECTURE 4 Python Basics Part 3 INPUT We ve already seen two useful functions for grabbing input from a user: raw_input() Asks the user for a string of input, and returns the string. If you provide an argument,

More information

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

ECE 364 Software Engineering Tools Lab. Lecture 8 Python: Advanced I ECE 364 Software Engineering Tools Lab Lecture 8 Python: Advanced I 1 Python Variables Namespaces and Scope Modules Exceptions Lecture Summary 2 More on Python Variables All variables in Python are actually

More information

CSc 120. Introduc/on to Computer Programing II. Adapted from slides by Dr. Saumya Debray. 01- a: Python review

CSc 120. Introduc/on to Computer Programing II. Adapted from slides by Dr. Saumya Debray. 01- a: Python review CSc 120 Introduc/on to Computer Programing II Adapted from slides by Dr. Saumya Debray 01- a: Python review python review: variables, expressions, assignment 2 python basics x = 4 y = 5 z = x + y x 4 y

More information

Errors. And How to Handle Them

Errors. And How to Handle Them Errors And How to Handle Them 1 GIGO There is a saying in computer science: Garbage in, garbage out. Is this true, or is it just an excuse for bad programming? Answer: Both. Here s what you want: Can you

More information

Python Tutorial. Day 2

Python Tutorial. Day 2 Python Tutorial Day 2 1 Control: Whitespace in perl and C, blocking is controlled by curly-braces in shell, by matching block delimiters, if...then...fi in Python, blocking is controlled by indentation

More information

CIS192 Python Programming

CIS192 Python Programming 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

More information

CIS192 Python Programming

CIS192 Python Programming 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

More information

FILE HANDLING AND EXCEPTIONS

FILE HANDLING AND EXCEPTIONS FILE HANDLING AND EXCEPTIONS INPUT We ve already seen how to use the input function for grabbing input from a user: input() >>> print(input('what is your name? ')) What is your name? Spongebob Spongebob

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1

More information

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS (download slides and.py files and follow along!) 6.0001 LECTURE 7 6.0001 LECTURE 7 1 WE AIM FOR HIGH QUALITY AN ANALOGY WITH SOUP You are making soup but bugs

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

CSc 120. Introduc/on to Computer Programming II. 02: Problem Decomposi1on and Program Development. Adapted from slides by Dr.

CSc 120. Introduc/on to Computer Programming II. 02: Problem Decomposi1on and Program Development. Adapted from slides by Dr. CSc 120 Introduc/on to Computer Programming II Adapted from slides by Dr. Saumya Debray 02: Problem Decomposi1on and Program Development A common student lament "I have this big programming assignment.

More information

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

More information

Algorithms and Programming

Algorithms and Programming Algorithms and Programming Lecture 4 Software design principles Camelia Chira Course content Introduction in the software development process Procedural programming Modular programming Abstract data types

More information

Exceptions. Exceptions. Can have multiple except suites and/or one unnamed except suite

Exceptions. Exceptions. Can have multiple except suites and/or one unnamed except suite Exceptions An exception is an error which occurs while a program is running. try-except statement: o monitor code that could produce an error o provide error-specific recovery code suite to handle specific

More information

Exceptions & a Taste of Declarative Programming in SQL

Exceptions & a Taste of Declarative Programming in SQL Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts

More information

What we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14

What we already know. more of what we know. results, searching for This 6/21/2017. chapter 14 What we already know chapter 14 Files and Exceptions II Files are bytes on disk. Two types, text and binary (we are working with text) open creates a connection between the disk contents and the program

More information

Debugging. BBM Introduc/on to Programming I. Hace7epe University Fall Fuat Akal, Aykut Erdem, Erkut Erdem, Vahid Garousi

Debugging. BBM Introduc/on to Programming I. Hace7epe University Fall Fuat Akal, Aykut Erdem, Erkut Erdem, Vahid Garousi Debugging BBM 101 - Introduc/on to Programming I Hace7epe University Fall 2015 Fuat Akal, Aykut Erdem, Erkut Erdem, Vahid Garousi Slides based on material prepared by Ruth Anderson, Michael Ernst and Bill

More information

Agenda. Excep,ons Object oriented Python Library demo: xml rpc

Agenda. Excep,ons Object oriented Python Library demo: xml rpc Agenda Excep,ons Object oriented Python Library demo: xml rpc Resources h?p://docs.python.org/tutorial/errors.html h?p://docs.python.org/tutorial/classes.html h?p://docs.python.org/library/xmlrpclib.html

More information

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

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions Outline 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating

More information

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

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 Files Files File I/O 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 open(file, mode='r', buffering=-1, encoding=none,...

More information

Lecture #12: Quick: Exceptions and SQL

Lecture #12: Quick: Exceptions and SQL 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

More information

Slide Set 15 (Complete)

Slide Set 15 (Complete) Slide Set 15 (Complete) for ENCM 339 Fall 2017 Section 01 Steve Norman, PhD, PEng Electrical & Computer Engineering Schulich School of Engineering University of Calgary November 2017 ENCM 339 Fall 2017

More information

MEIN 50010: Python Flow Control

MEIN 50010: Python Flow Control : Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-11 Program Overview Program Code Block Statements Expressions Expressions & Statements An expression has

More information

F21SC Industrial Programming: Python: Classes and Exceptions

F21SC Industrial Programming: Python: Classes and Exceptions F21SC Industrial Programming: Python: Classes and Exceptions Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2017/18 0 No proprietary software

More information

CSc 120. Introduc/on to Computer Programing II. 01- b: Python review. Adapted from slides by Dr. Saumya Debray

CSc 120. Introduc/on to Computer Programing II. 01- b: Python review. Adapted from slides by Dr. Saumya Debray CSc 120 Introduc/on to Computer Programing II Adapted from slides by Dr. Saumya Debray 01- b: Python review Lists of Lists x = [ [1,2,3], [4], [5, 6]] x [[1, 2, 3], [4], [5, 6]] y = [ ['aa', 'bb', 'cc'],

More information

Exceptions & error handling in Python 2 and Python 3

Exceptions & error handling in Python 2 and Python 3 Exceptions & error handling in Python 2 and Python 3 http://www.aleax.it/pycon16_eh.pdf 2016 Google -- aleax@google.com 1 Python in a Nutshell 3rd ed Chapter 5 of Early Release e-book version 50% off:

More information

4.3 FURTHER PROGRAMMING

4.3 FURTHER PROGRAMMING 4.3 FURTHER PROGRAMMING 4.3.3 EXCEPTION HANDLING EXCEPTION HANDLING An exception is a special condition that changes the normal flow of the program execution. That is, when an event occurs that the compiler

More information

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

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes Class definition F21SC Industrial Programming: Python Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2014/15 Class definition uses familiar

More information

Computer Science 9608 (Notes) Chapter: 4.3 Further programming

Computer Science 9608 (Notes) Chapter: 4.3 Further programming An exception is a special condition that changes the normal flow of the program execution. That is, when an event occurs that the compiler is unsure of how to deal with. Exceptions are the programming

More information

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

file_object=open( file_name.txt, mode ) f=open( sample.txt, w ) How to create a file: UNIT 5 FILES, MODULES AND PACKAGES Files: text files, reading and writing files, format operator, command line arguments, Errors and Exceptions: handling exceptions, Modules, Packages; Illustrative programs:

More information

A Little Python Part 3

A Little Python Part 3 A Little Python Part 3 Introducing Programming with Python I/O, Files, Object Classes, Exception Handling Outline I/O Files opening File I/O, reading writing Python Objects Defining a new object Inheritance

More information

Idioms and Anti-Idioms in Python

Idioms and Anti-Idioms in Python Idioms and Anti-Idioms in Python Release 2.6.3 Guido van Rossum Fred L. Drake, Jr., editor October 06, 2009 Python Software Foundation Email: docs@python.org Contents 1 Language Constructs You Should Not

More information

Chapter 9: Dealing with Errors

Chapter 9: Dealing with Errors Chapter 9: Dealing with Errors What we will learn: How to identify errors Categorising different types of error How to fix different errors Example of errors What you need to know before: Writing simple

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Review 3. Exceptions and Try-Except Blocks

Review 3. Exceptions and Try-Except Blocks Review 3 Exceptions and Try-Except Blocks What Might You Be Asked Create your own Exception class Write code to throw an exception Follow the path of a thrown exception Requires understanding of try-except

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Decision Structures Zelle - Chapter 7

Decision Structures Zelle - Chapter 7 Decision Structures Zelle - Chapter 7 Charles Severance - www.dr-chuck.com Textbook: Python Programming: An Introduction to Computer Science, John Zelle x = 5 print "Before 5 if ( x == 5 ) : print "Is

More information

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1 (remedial) Java anastasia.bezerianos@lri.fr Jars Anastasia Bezerianos 1 Disk organiza0on of Packages! Packages are just directories! For example! class3.inheritancerpg is located in! \remedialjava\src\class3\inheritencerpg!

More information

Computer Science 200b Exam 2 April 14, 2016

Computer Science 200b Exam 2 April 14, 2016 YOUR NAME PLEASE: NETID: Computer Science 200b Exam 2 April 14, 2016 Enter your netid at the bottom of each page. Closed book and closed notes. No electronic devices. Show ALL work you want graded on the

More information

A Little Python Part 3

A Little Python Part 3 A Little Python Part 3 Introducing Programming with Python I/O, Files, Object Classes, Exception Handling Outline I/O Files opening File I/O, reading writing Python Objects Defining a new object Inheritance

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

Final Exam Version A

Final Exam Version A CS112 Spring 2014 Dr. Kinga Dobolyi Final Exam Version A Do not open this exam until you are told. Read these instructions: 1. This is a closed book exam. No calculators, notes, or other aids are allowed.

More information

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

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013 CS61A Lecture 32 Amir Kamil UC Berkeley April 5, 2013 Announcements Hog revisions due Monday HW10 due Wednesday Make sure to fill out survey on Piazza We need to schedule alternate final exam times for

More information

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17 CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 1 Discussion Sections 02-08, 16, 17 Adapted from slides by Sue Evans et al. 2 Learning Outcomes Become familiar with input and output (I/O) from

More information

UNIVERSITETET I OSLO

UNIVERSITETET I OSLO UNIVERSITETET I OSLO Det matematisk-naturvitenskapelige fakultet Examination in: IN1900 Introduction to programming with scientific applications Day of examination: Tuesday, October 10, 2017 Examination

More information

Structure and Flow. CS 3270 Chapter 5

Structure and Flow. CS 3270 Chapter 5 Structure and Flow CS 3270 Chapter 5 Python Programs Are made up of modules One module is the main (top-level) module The first one loaded (even if it s the interpreter) Its module object has main as its

More information

CS 11 python track: lecture 4

CS 11 python track: lecture 4 CS 11 python track: lecture 4 Today: More odds and ends assertions "print >>" syntax more on argument lists functional programming tools list comprehensions More on exception handling More on object-oriented

More information

University of Texas at Arlington, TX, USA

University of Texas at Arlington, TX, USA Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA The set of program statements over which a variable exists (i.e. can be referred to) It is about understanding, for any

More information

Java Exceptions Version June 2009

Java Exceptions Version June 2009 Java Exceptions Version June 2009 Motivation Report errors, by delegating error handling to higher levels Callee might not know how to recover from an error Caller of a method can handle error in a more

More information

Lab 5: File I/O CSE/IT 107. NMT Computer Science

Lab 5: File I/O CSE/IT 107. NMT Computer Science CSE/IT 107 NMT Computer Science The danger that computers will become like humans is not as big as the danger that humans will become like computers. ( Die Gefahr, dass der Computer so wird wie der Mensch

More information

Introduction to Python programming, II

Introduction to Python programming, II GC3: Grid Computing Competence Center Introduction to Python programming, II (with a hint of MapReduce) Riccardo Murri Grid Computing Competence Center, University of Zurich Oct. 10, 2012 Today s class

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 7 Part 2 Instructor: Long Ma The Department of Computer Science Quick review one-way or simple decision if :

More information

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

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming File Operations Files are persistent data storage titanicdata.txt in PS06 Persistent vs. volatile memory. The bit as the unit of information. Persistent = data that is not dependent on a program (exists

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

Text Data, File I/O, and Exceptions

Text Data, File I/O, and Exceptions Text Data, File I/O, and Exceptions Strings, revisited Formatted output File Input/Output Errors and Exceptions String representations Introduction to Computing Using Python A string value is represented

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for This Lecture Assignments Prelim 2 A4 is now graded Mean: 90.4 Median: 93 Std Dev: 10.6 Mean: 9 hrs Median: 8 hrs Std Dev: 4.1 hrs A5 is also graded

More information

CSE : Python Programming

CSE : Python Programming CSE 399-004: Python Programming Lecture 2: Data, Classes, and Modules January 22, 2007 http://www.seas.upenn.edu/~cse39904/ Administrative things Teaching assistant Brian Summa (bsumma @ seas.upenn.edu)

More information

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)

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 Announcements Pairs Review Pairs and Lists In the late 1950s, computer scientists used confusing names cons: Two-argument procedure that creates a pair car: Procedure that returns the first

More information

Programming with Python

Programming with Python Programming with Python EOAS Software Carpentry Workshop September 21st, 2016 https://xkcd.com/353 Getting started For our Python introduction we re going to pretend to be a researcher studying inflammation

More information

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

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming File Operations Files are persistent data storage titanicdata.txt in PS07 Persistent vs. volatile memory. The bit as the unit of information. Persistent = data that is not dependent on a running program

More information

CSc 120. Introduction to Computer Programming II. 14: Stacks and Queues. Adapted from slides by Dr. Saumya Debray

CSc 120. Introduction to Computer Programming II. 14: Stacks and Queues. Adapted from slides by Dr. Saumya Debray CSc 120 Introduction to Computer Programming II Adapted from slides by Dr. Saumya Debray 14: Stacks and Queues linear data structures 2 Linear data structures A linear data structure is a collec6on of

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 7 Part 2 The Department of Computer Science Quick review one-way or simple decision if : two-way decision

More information

Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016

Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016 Chapter 6: Files and Exceptions COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016 Introduction to File Input and Output Concept: When a program needs to save data for later use, it writes the data in a

More information

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017 Chapter 6: Files and Exceptions COSC 1436, Spring 2017 Hong Sun 3/6/2017 Function Review: A major purpose of functions is to group code that gets executed multiple times. Without a function defined, you

More information

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Yue Li based on material from Mathieu Blanchette, Carlos Oliver Gonzalez and Christopher Cameron 1/29 Outline Quiz 14 review Set Commenting code Bugs 2/29 Quiz 15

More information

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19 1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object

More information

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

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

More information

Files. Reading from a file

Files. Reading from a file Files We often need to read data from files and write data to files within a Python program. The most common type of files you'll encounter in computational biology, are text files. Text files contain

More information

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Material from Carlos G. Oliver, Christopher J.F. Cameron October 12, 2018 1/31 Reminder CSUS is holding a midterm review session on Monday, October 15th, from 6-9pm.

More information

Teaching London Computing

Teaching London Computing Teaching London Computing A Level Computer Science Topic 3: Advanced Programming in Python William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims Further

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

Introduction to Python programming, II

Introduction to Python programming, II Grid Computing Competence Center Introduction to Python programming, II Riccardo Murri Grid Computing Competence Center, Organisch-Chemisches Institut, University of Zurich Nov. 16, 2011 Today s class

More information

61A Lecture 25. Friday, October 28

61A Lecture 25. Friday, October 28 61A Lecture 25 Friday, October 2 From Last Time: Adjoining to a Tree Set 5 9 7 3 9 7 11 1 7 11 Right! Left! Right! Stop! 5 9 7 3 9 7 11 1 7 11 2 From the Exam: Pruned Trees a b c d (a,b) (a,c) (a,d) pruned

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 9 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

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

CS 11 python track: lecture 3. n Today: Useful coding idioms CS 11 python track: lecture 3 Today: Useful coding idioms Useful coding idioms "Idiom" Standard ways of accomplishing a common task Using standard idioms won't make your code more correct, but more concise

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 10 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

Python for C programmers

Python for C programmers Python for C programmers The basics of Python are fairly simple to learn, if you already know how another structured language (like C) works. So we will walk through these basics here. This is only intended

More information

Lecture 18. Classes and Types

Lecture 18. Classes and Types Lecture 18 Classes and Types Announcements for Today Reading Today: See reading online Tuesday: See reading online Prelim, Nov 6 th 7:30-9:30 Material up to next class Review posted next week Recursion

More information

STSCI Python Introduction. Class URL

STSCI Python Introduction. Class URL STSCI Python Introduction Class 2 Jim Hare Class URL www.pst.stsci.edu/~hare Each Class Presentation Homework suggestions Example files to download Links to sites by each class and in general I will try

More information

Return Values SECTION /26/16 Page 33

Return Values SECTION /26/16 Page 33 Return Values SECTION 5.4 9/26/16 Page 33 Return Values Func%ons can (op%onally) return one value Add a return statement that returns a value A return statement does two things: 1) Immediately terminates

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

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

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

More information

logstack Documentation

logstack Documentation logstack Documentation Release 0.1 Remi Rampin Apr 08, 2017 Contents 1 Getting started 1 2 Contents 3 2.1 Reference................................................. 3 2.2 Internal reference.............................................

More information