Exceptions CS GMU
|
|
- Gabriel Cobb
- 5 years ago
- Views:
Transcription
1 Exceptions CS GMU
2 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 raised: ValueError, IndexError, KeyError, etc. we can selectively catch particular types, and recover normal control flow
3 quick example: try-except blocks n = int(input("how many inches?")) (feet, inches) = (n//12, n%12) print("that's %d feet, %d inches" % (feet, inches)) except: print("oops, that wasn't a number!") print("goodbye.") ex1.py Python attempts the try-block. If it succeeds (no exceptions raised), we skip the except-block and move on (print 'goodbye.') if any exception is raised, we immediately abort the entire try block and jump to the except-block (it catches all kinds of exceptions). The except block is run, and then fall out to print 'goodbye.'
4 immediate escaping if an exception is raised, we don't complete that expression, we don't complete that statement. be careful that might mean a variable doesn't exist, even after the try-except code! ex2.py choice = int(input("how much?")) print ("choice received.") except: print("oops.") # this might fail! choice might not exist. print(choice) Consider these inputs: hello
5 Some Common Exceptions Exception Type FileNotFoundError IndexError KeyError NameError SyntaxError TypeError ValueError ZeroDivisionError Description tried to open a non-existent file tried to index into a structure with a not-present index. tried to access non-existent key in a dictionary. identifier for a name couldn't be found in scope. syntax error encountered. type error encountered, e.g. argument to built-in is of wrong type. built-in function/operation received value of right type, but wrong value (e.g., int() received a str, but it didn't represent a number) tried to divide by zero. 5
6 Exceptions Hierarchy (excerpt) There are many exception classes organized into a hierarchy each name here is its own python type! indentations: indicates inheritance (parent/child relationships). A KeyError is a more specific kind of LookupError; it's allowed anywhere a LookupError is. abbreviated version of the hierarchy BaseException +-- KeyboardInterrupt +-- Exception +-- ArithmeticError +-- ZeroDivisionError +-- EnvironmentError +-- OSError +-- FileNotFountError +-- EOFError +-- LookupError +-- IndexError +-- KeyError +-- NameError +-- SyntaxError +-- SystemError +-- TypeError +-- ValueError (found at )
7 variations: multiple except blocks, multiple types per block import sys filename = sys.argv[1] f = open(filename) lines = f.readlines() f.close() xs = [] for line in lines: # file might not exist xs. append ( int(line) )# might not be an int. secret = xs[3] / xs[10] print("secret result:",secret) except FileNotFoundError: print("file didn't exist.") except (ValueError, IndexError) as e: print("bad input!", type(e), str(e)) # index might not exist except Exception as anyname: # any zero-division?? print("catch-all: unforseen! ", str(anyname)) print("end of example.") ex3.py Notes when exception occurs, only the first compatible except-block runs! Example details sys.argv lets us access the commandline arguments except block for FileNotFoundError didn't want to inspect the exception value; no as e clause needed. ValueError, IndexError, and any child classes of exceptions are all handled here. wanted to inspect the object, so as <name> clause included. except Exception block handles exceptions of type Exception and any child classes that's all exceptions!
8 variations we can inspect the exception value if desired: except SomeType as anyname: statements <can use anyname> we can ignore the particular value and still catch those types by skipping the as-clause: except SomeType: statements
9 variations we can have multiple except blocks. first block to handle the actual type of raised exception is the only one to run "parent" types of exceptions match all child types (the deeper indentations of that chart are child types) except Exception thus catches anything we can catch anything, and ignore the particular value, with a raw except: block
10 caution things can still crash any raised exception whose type isn't compatible with any of the except blocks will "escape": it crashes further, out of the next layer of try-blocks, function calls, until it either is caught elsewhere or crashes the entire program. xs = [5,10,15,20] ex4.py index = int(input("which spot? ")) val = xs[index] print("you chose "+str(val)) except ValueError: print("that wasn't an int.") print("end of program.") Sample Inputs: 2 # successful three # ValueError caught 39 # IndexError escapes!
11 POLL 8A basic try-except usage
12 Validating Input Loop continues to execute, raising and handling exceptions, until user complies. need_input = True ex5.py while need_input: n = int(input("#items: ")) fr = int(input("#friends: ")) each = n/fr need_input = False except Exception as e: print(e) print("everyone gets %s items." % each) sample calls demo$ python3 ex5.py #items: asdf invalid literal for int() with base 10: 'asdf' #items: 3 #friends: 0 division by zero #items: 10 #friends: 5 everyone gets 2.0 items.
13 validating input: alternate version We can use while True: and break with exceptions for a convenient way to escape: if any exceptions occur, we skip the break and the loop forces us to try again. need_input = True ex5.py while need_input: n = int(input("#items: ")) fr = int(input("#friends: ")) each = n/fr need_input = False except Exception as e: print(e) print("everyone gets %s items." % each) while True: ex5_alt.py n = int(input("#items: ")) fr = int(input("#friends: ")) each = n/fr break except Exception as e: print(e) print("everyone gets %s items." % each)
14 Practice Problem What happens if we instead had the while loop inside the try block, like this? practice1.py need_input = True while need_input: x = int(input("#: ")) need_input = False except Exception as e: print(e) print ("successfully got x: "+str(x))
15 Practice Problems Using exception handling (try-except): successfully get a positive integer from the user. write a function that accepts a message string, a list of acceptable int values. It then forces the user to supply one of those values, which is returned.
16 POLL 8B multiple exception blocks
17 try-except-else the else block only runs if no exceptions were raised in the tryblock (no except block ran) ex6.py v = int(input("? ")) d = {1:'a', 2:'b', 3:'c'} k = 12//v print(d[k]) except (ValueError, ZeroDivisionError) as e: print(e) else: print(" ") 17 sample behavior: demo$ python3 ex6.py? 12 a demo$ python3 ex6.py? asdf invalid literal for int() with base 10: 'asdf' demo$ python3 ex6.py? 3 Traceback (most recent call last): File "ex6.py", line 4, in <module> print(d[v]) KeyError: 4 demo$
18 try-except(s)-(else)-finally a finally-block always runs. - after successful try (and else) blocks. - after except-block - before uncaught exception keeps crashing ex7.py print(50 / (int(input("? ")))) except ZeroDivisionError as e: print(e) else: print("success!") finally: print("always runs.") 18 sample behavior demo$ python3 ex7.py? success! always runs. demo$ python3 ex7.py? 0 division by zero always runs. demo$ python3 ex7.py? asdf always runs. Traceback [truncated] ValueError: invalid literal
19 a bit of planned escaping we might write code that lets some types of exception escape whoever calls this code will be responsible for catching them def get_count(): ex8.py f = open("logfile.txt") return int(f.read()) except FileNotFoundError: return 100 def main(): n = get_count() except ValueError: n = 0 print("n =", n) main() Sample Usage when logfile.txt doesn't exist: get_count catches the FileNotFoundError prints n = 100 when logfile.txt contains "23": prints n = 23 when logfile.txt contains "hello": main catches the ValueError, prints n = 0 19
20 Practice Problem Write a function that accepts a file name, opens the file, and reads out a single integer from it. Handle a FileNotFoundError by returning -1, and let ValueErrors escape (don't handle them) show how to call the program and cause both types of errors, including what would be in the file when it is present.
21 Practice Problem Write a function that examines a list and checks if there are k values in a row that are identical. Rather than carefully stop exactly when necessary, try letting an index error be caught and ignored. "try more than enough, ignore the bad cases." def k_twins(xs, k):
22 POLL 8C extra exception features
23 Raising Exceptions We can generate an exception on purpose (and hopefully catch it somewhere else!) performed with a raise statement, which needs an expression of some Exception type. This usually means calling a constructor ( init method). Examples: raise Exception("boo!") raise ArithmeticError ("this doesn't add up!") raise ValueError("needed a positive number") except IOError as e: print ("catching it, re-raising it.") raise e
24 Raising Exceptions Reusing/raising a few specific exception types is useful: Exception for general issues (but a bit vague) TypeError, when the supplied arg. was the wrong type ValueError when your code only should be run on some batch of values and the wrong one was given(e.g., only works on positive integers) Any type can be used if it suits your purpose; just call the constructor (see examples on previous slide) Then you can raise them and catch them as before. you can also make your own brand-new types of exceptions!
25 Re-raising the Same Exception We can directly re-raise the caught exception object. No need to construct exception value; we already have one. def get_input(): ex9.py return float (input("#: ")) except ValueError as e: print("in get_input: "+str(e)) raise ValueError("ERR") def main(): print( get_input()) except ( ValueError) as e: print ("in main: "+str(e)) main() sample usage demo$ python3 ex9.py note the quotes! #: 'a' in get_input: could not convert string to float: 'a' in main: ERR 25
26 Practice Problem: Scenario A bridge inspector, Jon, is doing the yearly inspection for some bridge. He has a can of paint where he can touch up old paint, and he also has a "bridge closed" sign with him. He can also report to his supervisor. Jon sees a big rusty spot. He can: paint over it (is this 'solution' good enough?) quit inspecting and tell his supervisor put up the "bridge closed" sign, but also tell his supervisor. How do Jon's choices sound like exception handling approaches?
27 POLL 8D raising exceptions
28 User-Defined Exceptions (sneak peek at classes) We can create our own types of exceptions. They can be raised, propagated, and caught just like any other exception types. Just include Exception as the parent class as shown below (put Exception in parentheses after classname). We'll explore this more after learning classes. class BadInput(Exception): def init (self, value): self.value = value ex10.py 28
29 User-Defined Exceptions (sneak peek at classes) raise keyword used with a call to exception's constructor except-block used with our new type of exception from ex10 import BadInput ex11.py x = int(input("#? ")) if x==13: raise BadInput("that's unlucky!") print(x*10) except BadInput as e: print("uhoh: "+e.value) except Exception as e: print(e) sample usage demo$ python3 ex11.py #? 5 50 demo$ python3 ex11.py #? 13 uhoh: that's unlucky! demo$ python3 ex11.py #? asdf invalid literal for int() with base 10: 'asdf' 29
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 informationCSE : 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 informationException 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 informationClass 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 informationIntroduction 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 informationReview 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 informationClass 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 informationCSc 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 informationPython 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 informationExceptions & 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 informationLecture 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 informationSlide 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 informationLECTURE 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 informationFILE 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 informationWhat 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 informationOutline. 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 informationException 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 informationIntroduction 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 informationLecture 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 informationExceptions & 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 informationLecture #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 informationMEIN 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 informationECE 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 informationCIS192 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 informationChapter 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 informationCIS192 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 informationDEBUGGING 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 informationCS61A 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 informationCOMP1730/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 informationOverview. 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#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 informationCIS192 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 informationLecture 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 informationCIS192 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 informationCS 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 informationLecture 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 informationExceptions 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 informationF21SC 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 informationPython 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 informationGetting Started Values, Expressions, and Statements CS GMU
Getting Started Values, Expressions, and Statements CS 112 @ GMU Topics where does code go? values and expressions variables and assignment 2 where does code go? we can use the interactive Python interpreter
More information61A 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 informationClass 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 informationCS 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 informationCOMP519 Web Programming Lecture 20: Python (Part 4) Handouts
COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents
More informationModules 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 informationText Input and Conditionals
Text Input and Conditionals Text Input Many programs allow the user to enter information, like a username and password. Python makes taking input from the user seamless with a single line of code: input()
More informationSBT 645 Introduction to Scientific Computing in Sports Science #6
SBT 645 Introduction to Scientific Computing in Sports Science #6 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 informationfile_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 informationAbstract 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 informationPairs 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 informationCS Lecture 26: Grab Bag. Announcements
CS 1110 Lecture 26: Grab Bag Announcements The End is Nigh! 1. Next (last) lecture will be recap and final exam review 2. A5 due Wednesday night 3. Final exam 7pm Thursday May 15 in Barton Hall (East section)
More informationGIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes
GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and
More informationCS 11 Project #6 Due THURSDAY, December 7 th, 11:59pm. Classes and Exceptions Background: Classes allow us to define new types for Python. We can first think of a class as defining a new container instead
More informationCSE : 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 informationAn Introduction to Python
An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many
More informationNot-So-Mini-Lecture 6. Modules & Scripts
Not-So-Mini-Lecture 6 Modules & Scripts Interactive Shell vs. Modules Launch in command line Type each line separately Python executes as you type Write in a code editor We use Atom Editor But anything
More informationInteractive 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 informationAdvanced 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 informationTESTING, 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 informationOne of my favorite Python topics to talk about is error handling
DAVID BEAZLEY David Beazley is an open source developer and author of the Python Essential Reference (4th Edition, Addison-Wesley, 2009). He is also known as the creator of Swig (http://www.swig.org) and
More information61A Lecture 26. Monday, October 31
61A Lecture 26 Monday, October 31 Programming Languages Computers have software written in many different languages Machine languages: statements can be interpreted by hardware All data are represented
More informationCS 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 informationFunctions and Decomposition
Unit 4 Functions and Decomposition Learning Outcomes Design and implement functions to carry out a particular task. Begin to evaluate when it is necessary to split some work into functions. Locate the
More informationErrors. 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 informationCMSC 201 Fall 2016 Lab 09 Advanced Debugging
CMSC 201 Fall 2016 Lab 09 Advanced Debugging Assignment: Lab 09 Advanced Debugging Due Date: During discussion Value: 10 points Part 1: Introduction to Errors Throughout this semester, we have been working
More information1 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 informationHello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications
Hello World! Computer Programming for Kids and Other Beginners by Warren Sande and Carter Sande Chapter 1 Copyright 2009 Manning Publications brief contents Preface xiii Acknowledgments xix About this
More information1 Lecture 6: Conditionals and Exceptions
L6 June 16, 2017 1 Lecture 6: Conditionals and Exceptions CSCI 1360E: Foundations for Informatics and Analytics 1.1 Overview and Objectives In this lecture, we ll go over how to make "decisions" over the
More informationMITOCW watch?v=flgjisf3l78
MITOCW watch?v=flgjisf3l78 The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high-quality educational resources for free. To
More informationInteractive 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 informationPREPARING FOR PRELIM 1
PREPARING FOR PRELIM 1 CS 1110: FALL 2012 This handout explains what you have to know for the first prelim. There will be a review session with detailed examples to help you study. To prepare for the prelim,
More information12. 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 informationCOMP 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 informationThere 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 informationPython. Executive Summary
Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"
More informationTry and Error. Python debugging and beautification
Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords
More informationWhat 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 informationJava Bytecode (binary file)
Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.
More informationPython 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 informationCOMP 202 Java in one week
COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of
More informationGetting Started with Python
Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science
More informationA 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 informationJava for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B
Java for Python Programmers Comparison of Python and Java Constructs Reading: L&C, App B 1 General Formatting Shebang #!/usr/bin/env python Comments # comments for human readers - not code statement #
More informationCOMP 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 informationFundamentals of Programming (Python) Getting Started with Programming
Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science
More informationPython 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 informationPython 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 informationExceptions. 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 informationGetting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners
Getting Started Excerpted from Hello World! Computer Programming for Kids and Other Beginners EARLY ACCESS EDITION Warren D. Sande and Carter Sande MEAP Release: May 2008 Softbound print: November 2008
More informationPython 1: Intro! Max Dougherty Andrew Schmitt
Python 1: Intro! Max Dougherty Andrew Schmitt Computational Thinking Two factors of programming: The conceptual solution to a problem. Solution syntax in a programming language BJC tries to isolate and
More informationIntroduction 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 information4.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 informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More informationStarting. Read: Chapter 1, Appendix B from textbook.
Read: Chapter 1, Appendix B from textbook. Starting There are two ways to run your Python program using the interpreter 1 : from the command line or by using IDLE (which also comes with a text editor;
More information61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013
61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS Steven Tang and Eric Tzeng July 23, 2013 Announcements Regrades for project 1 composition scores, due by next Monday See Piazza post for more details Midterm
More informationSTSCI 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 informationCS 115 Lecture 4. More Python; testing software. Neil Moore
CS 115 Lecture 4 More Python; testing software Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 8 September 2015 Syntax: Statements A statement
More informationIdioms 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 informationCoral Programming Language Reference Manual
Coral Programming Language Reference Manual Rebecca Cawkwell, Sanford Miller, Jacob Austin, Matthew Bowers rgc2137@barnard.edu, {ja3067, skm2159, mlb2251}@columbia.edu October 15, 2018 Contents 1 Overview
More informationTeaching 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