SBT 645 Introduction to Scientific Computing in Sports Science #6

Size: px
Start display at page:

Download "SBT 645 Introduction to Scientific Computing in Sports Science #6"

Transcription

1 SBT 645 Introduction to Scientific Computing in Sports Science #6 SERDAR ARITAN Biyomekanik Araştırma Grubu Spor Bilimleri Fakültesi Hacettepe Universitesi, Ankara, Türkiye De Motu Animalium G.Borelli (1680) 1

2 General philosophy of errors and exception handling Any program may encounter errors during its execution. For the purposes of illustrating exceptions, we ll look at the case of a word processor that writes files to disk and that therefore may run out of disk space before all of its data is written. There are various ways of coming to grips with this problem. SOLUTION 1: DON T HANDLE THE PROBLEM The simplest way of handling this disk-space problem is to assume that there will always be adequate disk space for whatever files we write, and we needn t worry about it. Unfortunately, this seems to be the most commonly used option. It s usually tolerable for small programs dealing with small amounts of data, but it s completely unsatisfactory for more mission-critical programs. 2

3 General philosophy of errors and exception handling SOLUTION 2: ALL FUNCTIONS RETURN SUCCESS/FAILURE STATUS The next level of sophistication in error handling is to realize that errors will occur and to define a methodology using standard language mechanisms for detecting and handling them. There are various ways of doing this, but a typical one is to have each function or procedure return a status value that indicates if that function or procedure call executed successfully. Normal results can be passed back in a call-by-reference parameter. 3

4 General philosophy of errors and exception handling SOLUTION 3: THE EXCEPTION MECHANISM It s obvious that most of the error-checking code in the previous type of program is largely repetitive: it checks for errors on each attempted file write and passes an error status message back up to the calling procedure if an error is detected. The disk space error is handled in only one place, the top-level save_to_file. function save_to_file(filename) try to execute the following block save_text_to_file(filename) save_formats_to_file(filename) save_prefs_to_file(filename).... except that, if the disk runs out of space while executing the above block, do this...handle the error... 4

5 General philosophy of errors and exception handling The act of generating an exception is called raising or throwing an exception. The act of responding to an exception is called catching an exception, and the code that handles an exception is called exception-handling code, or just an exception handler. Depending on exactly what event causes an exception, a program may need to take different actions. For example, an exception raised when disk space is exhausted needs to be handled quite differently from an exception that is raised if we run out of memory, and both are completely different from an exception that arises when a divide-by-zero error occurs. 5

6 Getting an exception at the command line If the function in which the error occurred is implemented as a MATLAB program file, the error message should include a line that looks something like this: surf Error using surf (line 49) Not enough input arguments. The text includes the name of the function that threw the error (surf, in this case) and shows the failing line number within that function's program file. Click the line number; MATLAB opens the file and positions the cursor at the location in the file where the error originated. You may be able to determine the cause of the error by examining this line and the code that precedes it. 6

7 Getting an exception in your program code When you are writing your own program in a program file, you can catch exceptions and attempt to handle or resolve them instead of allowing your program to terminate. When you catch an exception, you interrupt the normal termination process and enter a block of code that deals with the faulty situation. This block of code is called a catch block. Some of the things you might want to do in the catch block are: Examine information that has been captured about the error. Gather further information to report to the user. Try to accomplish the task at hand in some other way. Clean up any unwanted side effects of the error. 7

8 Generating a new exception When your program code detects a condition that will either make the program fail or yield unacceptable results, it should throw an exception. This procedure Saves information about what went wrong and what code was executing at the time of the error. Gathers any other pertinent information about the error. Instructs MATLAB to throw the exception. 8

9 Exception Handling The MException Class The object has four properties: identifier, message, stack, and cause. Each of these properties is implemented as a field of the structure that represents the MException object. The syntax of the MException constructor is ME = MException(identifier, message) 9

10 try surf catch ME ME end Exception Handling ME = MException with properties: identifier: 'MATLAB:nargchk:notEnoughInputs' message: 'Not enough input arguments.' cause: {0x1 cell} stack: [1x1 struct] 10

11 Exception Handling try surf catch ME msg = ME.message; end msg = Not enough input arguments. 11

12 Exception Handling A Try-Catch block provides user-controlled error-trapping capabilities. That is, with a Try-Catch block, errors found by MATLAB are captured, giving the user the ability to control how MATLAB responds to errors. try catch end (commands 1) (commands 2) Here all MATLAB expression in ( commands 1 ) are executed. If no MATLAB errors are generated, control is passed to the end statement. However, if a MATLAB error appears while executing ( commands 1 ), control is immediately passed to the catch statement and subsequent expression ( commands 2 ). Within the catch block the function lasterr contains the string generated by the error encountered in the try block. 12

13 x = ones(4, 2); y = 4*eye(2); Exception Handling % y = 4*eye(3) % try the wrong one try z = x*y; catch z = nan; disp( x and y are not comformable ); end >> lasterr ans = Error using ==> * Inner matrix dimensions must agree. 13

14 Throw an Exception When your program detects a fault that will keep it from completing as expected or will generate erroneous results, you should halt further execution and report the error by throwing an exception. The basic steps to take are 1 Detect the error. This is often done with some type of conditional statement, such as an if or try/catch statement that checks the output of the current operation. 2 Construct an MException object to represent the error. Add a message identifier string and error message string to the object when calling the constructor. 3 If there are other exceptions that may have contributed to the current error, you can store the MException object for each in the cause field of a single MException that you intend to throw. Use the addcause method for this. 4 Use the throw or throwascaller function to have the MATLAB software issue the exception. 14

15 Exception Handling A = rand(3); B = ones(5); try C = [A; B]; catch err % Give more information for mismatch. if (strcmp(err.identifier,'matlab:catenate:dimensionmismatch')) msg = sprintf('%s',... 'Dimension mismatch occured: First argument has ',... num2str(size(a,2)), ' columns while second has ',... num2str(size(b,2)), ' columns.'); error('matlab:mycode:dimensions', msg); % Display any other errors as usual. else rethrow(err); end end % end try/catch 15

16 Working With Files The easiest way of writing and reading files in the MATLAB environment is by means of the functions save and load. While the former allows for saving all or some of the current workspace variables into a file, the latter allows for reading variables previously stored in a file and loading them into the workspace. By default, the two functions save and load, use the MATLAB proprietary format, in which variables names and their corresponding values are written to a formatted binary file with extension.mat 16

17 Working With Files >> clear % deletes all variables in the workspace >> a = [1 2; 3 4]; % creates some variables >> b = {'Hello','World','!'}; c.f1 = 'Hello'; c.f2 = 'World!'; >> save % saves the workspace into default file matlab.mat >> clear % deletes all variables in the workspace >> load % restores the workspace from default file matlab.mat >> whos Name Size Bytes Class Attributes a 2x2 32 double b 1x3 358 cell c 1x1 374 struct 17

18 Working With Files % save all variables into the file allworkspace.mat >> save('allworkspace'); >> % save only variables b and c into the file somevariables.mat >> save('somevariables','b','c'); >> clear % deletes all variables in the workspace % loads only variable a from the file allworkspace.mat >> load('allworkspace','a'); >> clear % deletes all variables in the workspace >> A = [1 2 3; 4 5 6]; >> save mydata.txt A ascii % To import (read) the array >> load mydata.txt >> A = load( mydata.txt ) 18

19 Working With Files The fopen function opens a file and returns a file id number for use with the file. fid = fopen(filename, permission) [fid, message] = fopen(filename, permission) [fid, message] = fopen(filename, permission, format) where filename is a string specifying the name of the file to open, permission is a character string specifying the mode in which the file is opened, and format is an optional string specifying the numeric format of the data in the file. If the open is successful, fid will contain a positive integer after this statement is executed and message will be empty string. If the open fails, fid will contain a -1 after this statement is executed, message will be a string explaining the error. The format string in the fopen function specifies the numeric format of the data is stored in the file. This string is only needed when transferring files between computers with incompatible numeric data formats, so it is rarely used. The fclose function close a file. status = fclose(fid) status = fclose( all ) where fid is a file id and status is the result of the operation. If the operation is successful, status will be zero. If it is unsuccessful status will be -1. fclose ( all ) closes all open files except for stdout(fid=1) and stderr(fid=2). 19

20 File Permission r r+ w w+ a a+ Format native or n ieee-le or l ieee-be or b Working With Files Meaning Open an existing file for reading only Open an existing file for reading and writing Delete the contents of an existing file (or create a new file) and open it for writing Delete the contents of an existing file (or create a new file) and open it for reading and writing Open an existing file (or create a new file) and open it for writing only, appending to the end of the file Open an existing file (or create a new file) and open it for reading and writing only, appending to the end of the file ieee-le.l64 or a ieee-le.l64 or s Meaning Numeric format for the machine MATLAB is executing on IEEE floating point with little-endian byte ordering IEEE floating point with big-endian byte ordering IEEE floating point with little-endian byte ordering and 64-bit long data type IEEE floating point with big-endian byte ordering and 64-bit long data type 20

21 Working With Files % ASCII File Access % open the file fid = fopen('square_mat.txt', 'wt'); % write the header fprintf(fid, '%s\n', 'This is a square matrix'); % write data to file fprintf(fid, '%i\t%i\t%i\n', [1 2 3; 4 5 6; 7 8 9]'); % close file fclose(fid); disp('write of file is successful!... press spacebar to continue') % read the file back in pause % open the file fid=fopen('square_mat.txt', 'rt'); % read in the header title = fgetl(fid); % read in data [data,count]=fscanf(fid, '%i',[3,3]); % close the file fclose(fid); 21

22 Working With Files 22

23 x = 0:.1:1; A = [x; exp(x)]; Working With Files fileid = fopen('exp.txt','w'); fprintf(fileid,'%6s %12s\n','x','exp(x)'); fprintf(fileid,'%6.2f %12.8f\n', A); fclose(fileid); >> id1 = fopen( data1, r ) id1 = 3 >> id2 = fopen( data2, r ) id2 = 4 23

24 Working With Files There are two MATLAB functions for reading and saving a very specific type of CSV files: csvwrite and csvread. These functions allow for writing and reading a matrix of numerical values into a CSV formatted file. In this sense, these functions are similar to save and load when the - ascii option is used, but different from them, the numerical values within each file line are separated by commas. >> mtx = rand(3,4); % creates a random-valued matrix of size 3x4 >> csvwrite('mtx.csv',mtx); % saves the matrix into a csv file >> type mtx.csv , , , , , , , , ,

25 Working With Files >> newmtx = csvread('mtx.csv') % loads the matrix into a new variable newmtx = Updated versions of csvwrite and csvread are implemented in dlmwrite and dlmread, which allow for specifying, as an additional input parameter, the delimiter character to be used for either writing or reading the file, respectively. However, similar to csvwrite and csvread, they are also restricted to numerical data. 25

26 Exception Handling Like everything else in Python, an exception is an object. It s generated automatically by Python functions with a raise statement. After it s generated, the raise statement, which raises an exception, causes execution of the Python program to proceed in a manner different than would normally occur. Instead of proceeding with the next statement after the raise, or whatever generated the exception, the current call chain is searched for a handler that can handle the generated exception. If such a handler is found, it s invoked and may access the exception object for more information. If no suitable exception handler is found, the program aborts with an error message. 26

27 Exception Handling Types of Python exceptions: It s possible to generate different types of exceptions to reflect the actual cause of the error or exceptional circumstance being reported. Python provides a number of different exception types: BaseException SystemExit KeyboardInterrupt GeneratorExit Exception StopIteration ArithmeticError FloatingPointError OverflowError ZeroDivisionError AssertionError AttributeError BufferError EnvironmentError IOError OSError WindowsError (Windows) VMSError (VMS) EOFError ImportError LookupError IndexError KeyError MemoryError NameError UnboundLocalError ReferenceError RuntimeError NotImplementedError SyntaxError IndentationError TabError SystemError TypeError ValueError UnicodeError UnicodeDecodeError UnicodeEncodeError UnicodeTranslateError 27

28 Exception Handling Different exception types 28

29 Exception Handling ValueError : input only number example 29

30 Exception Handling ZeroDivisionError : 30

31 Exception Handling ZeroDivisionError : 31

32 Exception Handling IOError and ValueError : 32

33 try Statement The try statement has another optional clause which is intended to define clean-up actions that must be executed under all circumstances. For example: A finally clause is always executed before leaving the try statement, whether an exception has occurred or not. 33

34 try Statement As you can see, the finally clause is executed in any event. In real world applications, the finally clause is useful for releasing external resources (such as files or network connections), regardless of whether the use of the resource was successful. 34

35 Hint : Changing directory is comes in very handy when working in the Python interpreter: >>> import os >>> os.getcwd() # Returns the current working directory 'C:\\Python33' # usually the directory you were in when you started the interpreter >>> os.chdir('/path/to/directory )) # Change the current working directory to 'path/to/directory' 35

36 Working With Files Python provides a built-in function open to open a file, which returns a file object f = open('foo.txt', 'r') # open a file in read mode f = open('foo.txt', 'w') # open a file in write mode f = open('foo.txt', 'a') # open a file in append mode 'b' appended to the mode opens the file in binary mode: 'rb', 'wb', 'ab' should be used to open a binary file in read, write and append mode respectively. This mode should be used for all files that don t contain text. open(filename, mode) The mode argument is optional; 'r' will be assumed if it s omitted. 36

37 Working With Files 37

38 Working With Files Easiest way to read contents of a file is by using the read method. >>> open('foo.txt').read() 'birinci satir\nikinci satir\nüçüncü satir >>> f.close() >>> print(open('foo.txt').read()) >>> birinci satir ikinci satir üçüncü satir >>> Contents of a file can be read line-wise using readline and readlines methods. >>> open('foo.txt').readlines() ['birinci satir\n', 'ikinci satir\n', 'üçüncü satir'] 38

39 Working With Files The readline method returns empty string when there is nothing more to read in a file. >>> f = open('foo.txt') >>> f.readline() 'birinci satir\n >>> f.readline() 'ikinci satir\n' >>> f.readline() 'üçüncü satir\n' >>> f.readline() >>> f.close() 39

40 Working With Files The write method is used to write data to a file opened in write or append mode >>> f = open('fooyaz.txt','w') >>> f.write('a\nb\nc') >>> f.close() 40

41 Working With Files The write method is used to write data to a file opened in append mode >>> f = open('fooyaz.txt', a') >>> f.write( d\n') >>> f.close() 41

42 Working With Files The writelines method is convenient to use when the data is available as a list of lines. >>> f = open('fooyaz.txt', a') >>> f.writelines(['a\n', 'b\n', 'c\n ]) >>> f.close() 42

43 Working With Files Lets try to compute the number of characters, words and lines in a file. Number of characters in a file is same as the length of its contents. >>>def charcount(filename): return len(open(filename).read()) Number of words in a file can be found by splitting the contents of the file. >>>def wordcount(filename): return len(open(filename).read().split()) Number of lines in a file can be found from readlines method >>>def linecount(filename): return len(open(filename).readlines()) 43

44 Working With Files >>> import os >>> os.getcwd() 'C:\\Python33' >>> os.chdir('f:\lectures\python') >>> charcount('bilgrafik.txt') 3206 >>> wordcount('bilgrafik.txt') 205 >>> linecount('bilgrafik.txt') 13 >>> 44

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

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

Exception Handling and Debugging

Exception Handling and Debugging Exception Handling and Debugging Any good program makes use of a language s exception handling mechanisms. There is no better way to frustrate an end-user then by having them run into an issue with your

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

Modules and scoping rules

Modules and scoping rules C H A P T E R 1 1 Modules and scoping rules 11.1 What is a module? 106 11.2 A first module 107 11.3 The import statement 109 11.4 The module search path 110 11.5 Private names in modules 112 11.6 Library

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

Beyond the Mouse A Short Course on Programming

Beyond the Mouse A Short Course on Programming 1 / 14 Beyond the Mouse A Short Course on Programming 5. Matlab IO: Getting data in and out of Matlab Ronni Grapenthin and Glenn Thompson Geophysical Institute, University of Alaska Fairbanks October 10,

More information

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : }

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : } Chapter 8 More Data Structures We have seen the list data structure and its uses. We will now examine two, more advanced data structures: the set and the dictionary. In particular, the dictionary is an

More information

CSE 123. Lecture 9. Formatted. Input/Output Operations

CSE 123. Lecture 9. Formatted. Input/Output Operations CSE 123 Lecture 9 Formatted Input/Output Operations fpintf function writes formatted data in a user specified format to a file fid fprintf Function Format effects only the display of variables not their

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

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

Chapter 11 Input/Output (I/O) Functions

Chapter 11 Input/Output (I/O) Functions EGR115 Introduction to Computing for Engineers Input/Output (I/O) Functions from: S.J. Chapman, MATLAB Programming for Engineers, 5 th Ed. 2016 Cengage Learning Topics Introduction: MATLAB I/O 11.1 The

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

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

5. MATLAB I/O 1. Beyond the Mouse GEOS 436/636 Jeff Freymueller, Sep 26, The Uncomfortable Truths Well, hop://xkcd.com/568 (April 13, 2009)

5. MATLAB I/O 1. Beyond the Mouse GEOS 436/636 Jeff Freymueller, Sep 26, The Uncomfortable Truths Well, hop://xkcd.com/568 (April 13, 2009) 5. MATLAB I/O 1 Beyond the Mouse GEOS 436/636 Jeff Freymueller, Sep 26, 2017 The Uncomfortable Truths Well, hop://xkcd.com/568 (April 13, 2009) Topics Loading and Saving the Workspace File Access Plo$ng

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

SBT 645 Introduction to Scientific Computing in Sports Science #3

SBT 645 Introduction to Scientific Computing in Sports Science #3 SBT 645 Introduction to Scientific Computing in Sports Science #3 SERDAR ARITAN serdar.aritan@hacettepe.edu.tr Biyomekanik Araştırma Grubu www.biomech.hacettepe.edu.tr Spor Bilimleri Fakültesi www.sbt.hacettepe.edu.tr

More information

SBT 645 Introduction to Scientific Computing in Sports Science #5

SBT 645 Introduction to Scientific Computing in Sports Science #5 SBT 645 Introduction to Scientific Computing in Sports Science #5 SERDAR ARITAN serdar.aritan@hacettepe.edu.tr Biyomekanik Araştırma Grubu www.biomech.hacettepe.edu.tr Spor Bilimleri Fakültesi www.sbt.hacettepe.edu.tr

More information

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

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

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

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

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

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

ES 117. Formatted Input/Output Operations

ES 117. Formatted Input/Output Operations ES 117 Formatted Input/Output Operations fpintf function writes formatted data in a user specified format to a file fid fprintf Function Format effects only the display of variables not their values through

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

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

Overview. Recap of FP Classes Instances Inheritance Exceptions

Overview. Recap of FP Classes Instances Inheritance Exceptions Overview Recap of FP Classes Instances Inheritance Exceptions [len(s) for s in languages] ["python", "perl", "java", "c++"] map(len, languages) < 6, 4, 4, 3> [num for num in fibs if is_even(num)] [1, 1,

More information

Using files. Computer Programming for Engineers (2014 Spring)

Using files. Computer Programming for Engineers (2014 Spring) Computer Programming for Engineers (2014 Spring) Using files Hyoungshick Kim Department of Computer Science and Engineering College of Information and Communication Engineering Sungkyunkwan University

More information

Importing and Exporting Data

Importing and Exporting Data Class14 Importing and Exporting Data MATLAB is often used for analyzing data that was recorded in experiments or generated by other computer programs. Likewise, data that is produced by MATLAB sometimes

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

#11: File manipulation Reading: Chapter 7

#11: File manipulation Reading: Chapter 7 CS 130R: Programming in Python #11: File manipulation Reading: Chapter 7 Contents File manipulation Text ASCII files Binary files - pickle Exceptions File manipulation Electronic files Files store useful

More information

Exceptions and File I/O

Exceptions and File I/O Lab 6 Exceptions and File I/O Lab Objective: In Python, an exception is an error detected during execution. Exceptions are important for regulating program usage and for correctly reporting problems to

More information

Reading and writing files

Reading and writing files C H A P T E R 1 3 Reading and writing files 131 Opening files and file objects 131 132 Closing files 132 133 Opening files in write or other modes 132 134 Functions to read and write text or binary data

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

MATLAB User-defined functions, Data Input/Output. Edited by Péter Vass

MATLAB User-defined functions, Data Input/Output. Edited by Péter Vass MATLAB User-defined functions, Data Input/Output Edited by Péter Vass User-defined functions Although, MATLAB provides a wide range of built-in functions it may often be necessary to create and use an

More information

Matlab Programming Arrays and Scripts 1 2

Matlab Programming Arrays and Scripts 1 2 Matlab Programming Arrays and Scripts 1 2 Mili I. Shah September 10, 2009 1 Matlab, An Introduction with Applications, 2 nd ed. by Amos Gilat 2 Matlab Guide, 2 nd ed. by D. J. Higham and N. J. Higham Matrix

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

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

Fö 6: Filhantering. DN1212 Numeriska metoder och grundläggande programmering. Pawel Herman. KTH/CB

Fö 6: Filhantering. DN1212 Numeriska metoder och grundläggande programmering. Pawel Herman. KTH/CB Fö 6: Filhantering DN1212 Numeriska metoder och grundläggande programmering paherman@kth.se KTH/CB 22 februari Pawel 2013Herman Lecture outline Recapitulation of what we already know about I/O Matlab format

More information

There is also a more in-depth GUI called the Curve Fitting Toolbox. To run this toolbox, type the command

There is also a more in-depth GUI called the Curve Fitting Toolbox. To run this toolbox, type the command Matlab bootcamp Class 4 Written by Kyla Drushka More on curve fitting: GUIs Thanks to Anna (I think!) for showing me this. A very simple way to fit a function to your data is to use the Basic Fitting GUI.

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

An Introductory Tutorial on Matlab

An Introductory Tutorial on Matlab 1. Starting Matlab An Introductory Tutorial on Matlab We follow the default layout of Matlab. The Command Window is used to enter MATLAB functions at the command line prompt >>. The Command History Window

More information

13-Writing Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

13-Writing Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie 13-Writing Data text: Chapter 4.4-4.5 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie Overview Writing Data to.txt Writing Data to.xls and.csv Writing Data to.mat Dr. Henry Louie

More information

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

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:

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

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

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

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

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

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

Lecture 5: Strings, Printing, and File I/O

Lecture 5: Strings, Printing, and File I/O 1 Lecture 5: Strings, Printing, and File I/O 1 Learning objectives At the of this class you should be able to... be able to name the three Matlab data types most commonly used in ME 352 be able to use

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

SBT 645 Introduction to Scientific Computing in Sports Science

SBT 645 Introduction to Scientific Computing in Sports Science SBT 645 Introduction to Scientific Computing in Sports Science SERDAR ARITAN serdar.aritan@hacettepe.edu.tr Biyomekanik Araştırma Grubu www.biomech.hacettepe.edu.tr Spor Bilimleri Fakültesi www.sbt.hacettepe.edu.tr

More information

12-Reading Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

12-Reading Data text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie 12-Reading Data text: Chapter 4.4-4.5 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie Overview Reading Data from.txt Reading Data from.xls and.csv Reading Data from.mat User Interface

More information

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

CSc 120. Introduction to Computer Programming II. 07: Excep*ons. Adapted from slides by Dr. Saumya Debray CSc 120 Introduction to Computer Programming II Adapted from slides by Dr. Saumya Debray 07: Excep*ons EXERCISE Type in the following code: def foo(): n = int(input("enter a number:")) print("n = ", n)

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

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

Spring 2010 Instructor: Michele Merler.

Spring 2010 Instructor: Michele Merler. Spring 2010 Instructor: Michele Merler http://www1.cs.columbia.edu/~mmerler/comsw3101-2.html Type from command line: matlab -nodisplay r command Tells MATLAB not to initialize the visual interface NOTE:

More information

Lecture 8: A cure for what ails you

Lecture 8: A cure for what ails you Lecture 8: A cure for what ails you When human beings acquired language, we learned not just how to listen but how to speak. When we gained literacy, we learned not just how to read but how to write.

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

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 #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

bioengineering-book Documentation

bioengineering-book Documentation bioengineering-book Documentation Release 0.1 Thiranja Prasad Babarenda Gamage Sep 15, 2017 Contents 1 Introduction 3 2 Linux FAQ 5 2.1 Find files in a terminal..........................................

More information

SCHEME INTERPRETER GUIDE 4

SCHEME INTERPRETER GUIDE 4 SCHEME INTERPRETER GUIDE 4 COMPUTER SCIENCE 61A July 28, 2014 1 Scheme Values Back in Python, we had all these objects (i.e. lists, tuples, strings, integers) which inherited from the superclass object.

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

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

PROGRAMMING WITH MATLAB WEEK 13

PROGRAMMING WITH MATLAB WEEK 13 PROGRAMMING WITH MATLAB WEEK 13 FILE INPUT AND OUTPUT Input statements read in values from the default or standard input device. In most systems the default input device is the keyboard. The input expression

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

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

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 7. MATLAB and Numerical Analysis (4)

Lecture 7. MATLAB and Numerical Analysis (4) Lecture 7 MATLAB and Numerical Analysis (4) Topics for the last 2 weeks (Based on your feedback) PDEs How to email results (after FFT Analysis (1D/2D) Advanced Read/Write Solve more problems Plotting3Dscatter

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

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

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

Introduction to MATLAB

Introduction to MATLAB Chapter 1 Introduction to MATLAB 1.1 Software Philosophy Matrix-based numeric computation MATrix LABoratory built-in support for standard matrix and vector operations High-level programming language Programming

More information

Programming in Mathematics. Mili I. Shah

Programming in Mathematics. Mili I. Shah Programming in Mathematics Mili I. Shah Starting Matlab Go to http://www.loyola.edu/moresoftware/ and login with your Loyola name and password... Matlab has eight main windows: Command Window Figure Window

More information

Basic Plotting. All plotting commands have similar interface: Most commonly used plotting commands include the following.

Basic Plotting. All plotting commands have similar interface: Most commonly used plotting commands include the following. 2D PLOTTING Basic Plotting All plotting commands have similar interface: y-coordinates: plot(y) x- and y-coordinates: plot(x,y) Most commonly used plotting commands include the following. plot: Draw a

More information

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

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

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

Access to Delimited Text Files

Access to Delimited Text Files Access to Delimited Text Files dlmread(filename, delimiter) reads ASCII-delimited file of numeric data. dlmwrite(filename, M, delimiter) writes the array M to the file using the specified delimiter to

More information

Python Working with files. May 4, 2017

Python Working with files. May 4, 2017 Python Working with files May 4, 2017 So far, everything we have done in Python was using in-memory operations. After closing the Python interpreter or after the script was done, all our input and output

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

Analysis Methods in Atmospheric and Oceanic Science AOSC 652. Introduction to MATLAB. Week 8, Day Oct 2014

Analysis Methods in Atmospheric and Oceanic Science AOSC 652. Introduction to MATLAB. Week 8, Day Oct 2014 Analysis Methods in Atmospheric and Oceanic Science 1 AOSC 652 Introduction to MATLAB Week 8, Day 1 20 Oct 2014 2 Introduction to MATLAB Matlab stands for MATrix LABoratory. Developed by http://www.mathworks.com/

More information

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

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except 12. Logical Maneuvers Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except Loop-Body Returns Loop-Body Returns Another way to terminate a loop. Uses the fact that in a function, control

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

Interactive MATLAB use. Often, many steps are needed. Automated data processing is common in Earth science! only good if problem is simple

Interactive MATLAB use. Often, many steps are needed. Automated data processing is common in Earth science! only good if problem is simple Chapter 2 Interactive MATLAB use only good if problem is simple Often, many steps are needed We also want to be able to automate repeated tasks Automated data processing is common in Earth science! Automated

More information

Low-Level File I/O. 1. Open a file. 2. Read or write data into the file. 3. Close the file. Zheng-Liang Lu 1 / 14

Low-Level File I/O. 1. Open a file. 2. Read or write data into the file. 3. Close the file. Zheng-Liang Lu 1 / 14 Low-Level File I/O Low-level file I/O functions allow the most control over reading or writing data to a file. However, these functions require that you specify more detailed information about your file

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

EXCEPTIONS, CALCULATOR 10

EXCEPTIONS, CALCULATOR 10 EXCEPTIONS, CALCULATOR 10 COMPUTER SCIENCE 61A November 5th, 2012 We are beginning to dive into the realm of interpreting computer programs - that is, writing programs that understand programs. In order

More information

ENG Introduction to Engineering

ENG Introduction to Engineering GoBack ENG 100 - Introduction to Engineering Lecture # 9 Files, Sounds, Images and Movies Koç University ENG 100 - Slide #1 File Handling MATLAB has two general ways of importing/exporting data from the

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

1 >> Lecture 6 2 >> 3 >> -- User-Controlled Input and Output 4 >> Zheng-Liang Lu 367 / 400

1 >> Lecture 6 2 >> 3 >> -- User-Controlled Input and Output 4 >> Zheng-Liang Lu 367 / 400 1 >> Lecture 6 2 >> 3 >> -- User-Controlled Input and Output 4 >> Zheng-Liang Lu 367 / 400 American Standard Code for Information Interchange (ASCII) 2 Everything in the computer is encoded in binary.

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 9 Date:

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

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment. Lecture 12 CSE 110 20 July 1992 Today we ll cover the things that you still don t know that you need to know in order to do the assignment. 1 The NULL Pointer For each pointer type, there is one special

More information

Dr Richard Greenaway

Dr Richard Greenaway SCHOOL OF PHYSICS, ASTRONOMY & MATHEMATICS 4PAM1008 MATLAB 3 Creating, Organising & Processing Data Dr Richard Greenaway 3 Creating, Organising & Processing Data In this Workshop the matrix type is introduced

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

Programming in Python 3

Programming in Python 3 Programming in Python 3 Programming transforms your computer from a home appliance to a power tool Al Sweigart, The invent with Python Blog Programming Introduction Write programs that solve a problem

More information