Head First Python: Ch 3. Files and Exceptions: Dealing with Errors Aug 26, 2013 Kyung-Bin Lim.

Slides:



Advertisements
Similar presentations
CS102--Object Oriented Programming
Advertisements

Head First Python Chapter 4 Persistence: Saving Data to Files SNU IDB Lab.
Debugging Introduction to Computing Science and Programming I.
How to Debug VB .NET Code.
Introduction to Python
Debugging CMSC 201. Announcements Hw2, Hw3 grades returned if something doesn’t seem right, ask Midterm next Thurs (Oct 23) we’ll review on Tues no hw.
Guide To UNIX Using Linux Third Edition
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
General Programming Introduction to Computing Science and Programming I.
Chapter 2 Adding Animation to a Presentation. Applying Animation Animation is a great way to add life to InDesign documents by making objects: – move.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Python File Handling. In all the programs you have made so far when program is closed all the data is lost, but what if you want to keep the data to use.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Creating your first C++ program
Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors.
1 Κατανεμημένες Διαδικτυακές Εφαρμογές Πολυμέσων Γιάννης Πετράκης.
Built-in Data Structures in Python An Introduction.
Chapter 5 Files and Exceptions I. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. What is a file? A.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
Files Tutor: You will need ….
Intermediate 2 Computing Unit 2 - Software Development.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Python Let’s get started!.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
The single most important skill for a computer programmer is problem solving Problem solving means the ability to formulate problems, think creatively.
CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.
INLS 560 – S TRINGS Instructor: Jason Carter. T YPES int list string.
JavaScript Introduction and Background. 2 Web languages Three formal languages HTML JavaScript CSS Three different tasks Document description Client-side.
AVCE ICT – Unit 7 - Programming Session 12 - Debugging.
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Python: File Directories What is a directory? A hierarchical file system that contains folders and files. Directory (root folder) Sub-directory (folder.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
COP Topics Java Basics - How to write & call your own method - Math methods (static methods) - String methods (instance methods) - Errors Classes.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
Development Environment
Introduction to Computing Science and Programming I
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Functions CIS 40 – Introduction to Programming in Python
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Exceptions and files Taken from notes by Dr. Neil Moore
Selection CIS 40 – Introduction to Programming in Python
File Handling Programming Guides.
Topics Introduction to File Input and Output
Lesson 04: Conditionals Class Chat: Attendance: Participation
Common C Programming Errors, GDB Debugging
File IO and Strings CIS 40 – Introduction to Programming in Python
Exceptions and files Taken from notes by Dr. Neil Moore
Winter 2018 CISC101 12/1/2018 CISC101 Reminders
ERRORS AND EXCEPTIONS Errors:
Remembering lists of values lists
Python programming exercise
CISC101 Reminders All assignments are now posted.
Passing Simple and Complex Parameters In and Out of Macros
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
CSE 231 Lab 5.
Topics Introduction to File Input and Output
CMSC 202 Exceptions.
IST256 : Applications Programming for Information Systems
Presentation transcript:

Head First Python: Ch 3. Files and Exceptions: Dealing with Errors Aug 26, 2013 Kyung-Bin Lim

2 / 21 Outline  Data is external to your program  It’s all lines of text  Take a closer look at the data  Know your data  Know your methods and ask for help  Modified code  Know your data (better)  Two very different approaches  First approach: Add extra logic  First approach: Code  Second approach: Try first, then recover  Second approach: Code  What if file doesn’t exist?  Using another level of exception handling  Conclusion: So which is better?

3 / 21 Data is external to your program  Most of your programs conform to the input-output model; data comes in, gets manipulated, and then stored, displayed, printed, or transferred  So far, you’ve learned how to process data as well as display it on screen  But, HOW does Python read data from a file?

4 / 21 It’s all lines of text  The basic input mechanism in Phython is line based: when read into your program from a text file, data arrives one line at a time  Python’s open() function lives to interact with files. When combined with a for statement, reading file is straightforward. the_file = open(‘sketch.txt) # Do something with the data # in “the_file” The_file = close()

5 / 21 Exercise  Start an IDEL session and import the OS to move to the correct directory import os os.getcwd() os.chdir(‘... your file directory…’)  Now, open your data file and read the first two lines from the file data = open(‘sketch.txt’) print(data.readline(), end=‘’) Man: Is this the right room for an argument? print(data.readline(), end=‘’) Other Man: I've told you once.

6 / 21 Exercise  Let’s rewind the file back to the start data.seek(0)  You can read every line in the file using for statement for each_line in data: print(each_line, end=‘’)

7 / 21 Take a closer look at the data  Look closely at the data. It appears to conform to a specific format.

8 / 21 Take a closer look at the data  With this format in mind, you can process each line to extract parts of the line as required. the split() method can help here:  The split() method returns a list of string, which are assigned to a list of target identifiers. This is known as multiple assignments. (role, line_spoken) = each_line.split(“:”)

9 / 21 Exercise

10 / 21 Know your data  Your code worked fine for a while, then crashed with a runtime error.  Let’s look at the data file and see where it crashed.  The line has TWO colons! This caused split() method to crash, since our code currently expects it to break the line into two parts.  When there is two colons, the split() method breaks the line into three parts and our code doesn’t know what to do if it gets three pieces of string. So is raises a ValueError.

11 / 21 Know your methods and ask for help  help() tells you more about BIF methods  The optional argument to split() controls how many breaks occur  By default, the data is broken into as many parts as is possible  Since we need only two parts, we will set it to 1

12 / 21 Modified code

13 / 21 Know your data (better)  Your code has raised another ValueError.  Problem: Some of the lines of data contain no colon, which causes a problem when the split() method goes looking for it. The lack of a colon prevents split() from doing its job, causes the runtime error, which then results in the complaint that the interpreter needs “more than 1 value.”

14 / 21 Two very different approaches  First approach: Add extra logic required work out whether it’s worth invoking split() on the line of data  Second approach: Let the error occur, then simply handle each error if and when it happens

15 / 21 First approach: Add extra logic  find() method finds location of a substring in another string, and if it can’t be found, the find() method returns the value -1. If the method locates the substring, it returns the index of the substring

16 / 21 First approach: Code

17 / 21 Second approach: Try first, then recover  Exception handling: Lets the error occur, spots that it has happened, and then recover  try/except mechanism: A way to systematically handle exceptions and errors at runtime

18 / 21 Second approach: Code

19 / 21 What if file doesn’t exist?  Python’s OS module has exist() method that can help determine whether a data file exists.

20 / 21 Using another level of exception handling

21 / 21 Conclusion: So which is better?  First approach (adding more logic/code) – Too complex – Code gets longer and complicated  Second approach (exception handling) – Simple – You can concentrate on what your code needs to do – Easier to read, write, and fix