Advanced Python Concepts: Exceptions

Slides:



Advertisements
Similar presentations
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Advertisements

I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
10/6/2014BCHB Edwards Sequence File Parsing using Biopython BCHB Lecture 11.
Python (yay!) November 16, Unit 7. Recap We can store values in variables using an assignment statement >>>x = We can get input from the user using.
The if statement and files. The if statement Do a code block only when something is True if test: print "The expression is true"
General Programming Introduction to Computing Science and Programming I.
Python – May 17 Recap lab Multidimensional list Exceptions Commitment: quiz tomorrow.
Sorting and Modules. Sorting Lists have a sort method >>> L1 = ["this", "is", "a", "list", "of", "words"] >>> print L1 ['this', 'is', 'a', 'list', 'of',
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?
CIT 590 Intro to Programming Lecture 4. Agenda Doubts from HW1 and HW2 Main function Break, quit, exit Function argument names, scope What is modularity!
9/16/2015BCHB Edwards Introduction to Python BCHB Lecture 5.
Chapter 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
10/20/2014BCHB Edwards Advanced Python Concepts: Modules BCHB Lecture 14.
9/14/2015BCHB Edwards Introduction to Python BCHB Lecture 4.
9/28/2015BCHB Edwards Basic Python Review BCHB Lecture 8.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
11/4/2015BCHB Edwards Advanced Python Concepts: Object Oriented Programming BCHB Lecture 17.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.
Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Lecture 4 Python Basics Part 3.
Python Exceptions and bug handling Peter Wad Sackett.
11/9/2015BCHB Edwards Advanced Python Concepts: OOP & Inheritance BCHB Lecture 18.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Sequence File Parsing using Biopython
Introduction to Python
Lesson 06: Functions Class Participation: Class Chat:
Exceptions in Python Error Handling.
Introduction to Computing Science and Programming I
Introduction to Python
George Mason University
Example: Vehicles What attributes do objects of Sedan have?
Advanced Python Concepts: Modules
Lecture 4 Python Basics Part 3.
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Advanced Python Concepts: Object Oriented Programming
Advanced Python Concepts: OOP & Inheritance
Exceptions and files Taken from notes by Dr. Neil Moore
Sequence File Parsing using Biopython
Conditionals (if-then-else)
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Exception Handling.
Python’s Errors and Exceptions
Basic Python Review BCHB524 Lecture 8 BCHB524 - Edwards.
Exceptions and files Taken from notes by Dr. Neil Moore
Lecture 4 Python Basics Part 3.
Advanced Python Concepts: OOP & Inheritance
Coding Concepts (Basics)
Advanced Python Concepts: Object Oriented Programming
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Input from the Console This video shows how to do CONSOLE input.
Introduction to Python
Python programming exercise
Advanced Python Concepts: Exceptions
Introduction to Python
Advanced Python Concepts: Modules
Advanced Python Concepts: OOP & Inheritance
Introduction to Python
Basic Python Review BCHB524 Lecture 8 BCHB524 - Edwards.
Introduction to Python
Advanced Python Concepts: Modules
Advanced Python Concepts: Object Oriented Programming
Sequence File Parsing using Biopython
Exception Handling COSC 1323.
Topics Introduction to File Input and Output
Python Exceptions and bug handling
IST256 : Applications Programming for Information Systems
Presentation transcript:

Advanced Python Concepts: Exceptions BCHB524 Lecture 16 BCHB524 - Edwards

Exceptions How to handle errors at run-time? KeyError is an exception we've seen a lot! compl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'} print compl_dict print compl_dict['X'] BCHB524 - Edwards

Exceptions How to handle errors at run-time? IndexError is an exception we've seen a lot! alist = [1,2,3,4,5] print alist print alist[10] BCHB524 - Edwards

Exceptions How to handle errors at run-time? ValueError is an exception we've seen a lot! shouldBeAnInt = 'jkfldsjlfalsjfdalja' print int(shouldBeAnInt) BCHB524 - Edwards

Exceptions In some cases, we can program around these potential errors: compl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'} print compl_dict if 'X' in compl_dict:     print compl_dict['X'] alist = [1,2,3,4,5] print alist if len(alist) > 10:     print alist[10] BCHB524 - Edwards

Exceptions But others are much more difficult: Traditionally, folks have used regular expressions to check these types of things. intstr = '1 4 bad integer' good = True for c in intstr:     if c not in '0123456789':         good = False         break if not good:     print "Not an integer" else:     print int(intstr) BCHB524 - Edwards

Exceptions Python provides the "try/except" block for these (and other) run-time errors. compl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'} alist = [1,2,3,4,5] intstr = 'fdjklsafjlajflajlfa' try:     print compl_dict['X'] except KeyError:     print "No such nucleotide" try:     print alist[10] except IndexError:     print "List is too short" try:     print int(intstr) except ValueError:     print "Not an integer"     BCHB524 - Edwards

Exceptions If you know what you are doing, you can ignore the error! (pass means "do nothing") compl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'} alist = [1,2,3,4,5] intstr = 'fdjklsafjlajflajlfa' try:     print compl_dict['X'] except KeyError:     pass try:     print alist[10] except IndexError:     pass try:     print int(intstr) except ValueError:     pass BCHB524 - Edwards

Exceptions except by itself catches any error... ...usually this is a bad idea! compl_dict = {'A':'T', 'T':'A', 'C':'G', 'G':'C'} try:     print compl_dict['X'] except:     print "Exception occurred" try:     print compl_dict['X'] except KeyError:     print "KeyError exception occurred" BCHB524 - Edwards

Exceptions can really simplify things! Do you understand how this automatically converts strings to their correct type? line = '1,3.2,abcdef,-1,1.3e+20,  -.4  ,  +10   ,e+20' for valstr in line.split(','):     try:         value = valstr         value = float(valstr)         value = int(valstr)     except ValueError:         pass     print repr(valstr),type(value),value BCHB524 - Edwards

Exceptions can really simplify things! # Import the required modules import sys import os.path # Check there is user input if len(sys.argv) < 2:     print "Please provide a DNA sequence file",     print "on the command-line."     sys.exit(1) # Assign the user input to variables seqfile = sys.argv[1] if not os.path.exists(seqfile):     print "Can't find sequence file:",seqfile     sys.exit(1) # define functions def readseq(filename):     return ''.join(open(seqfile).read().split()) seq = readseq(seqfile) # rest of program print seq BCHB524 - Edwards

Exceptions can really simplify things! # Import the required modules import sys # define functions def readseq(filename):     return ''.join(open(seqfile).read().split()) try:     seqfile = sys.argv[1]     seq = readseq(seqfile) except IndexError:     print "Please provide a DNA sequence file",     print "on the command-line."     sys.exit(1) except IOError:     print "Can't find sequence file:",seqfile     sys.exit(1) # rest of program print seq BCHB524 - Edwards

Exercise Add some try/except blocks in your DNA and codon_table modules from Lecture 15. ...but only where a try/except block is a useful simplification of the code. BCHB524 - Edwards