CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.

Slides:



Advertisements
Similar presentations
CSC 110 Decision structures [Reading: chapter 7] CSC 110 H1.
Advertisements

1 Decision Structures Chapter 7 (Skip 7.1.3, 7.4) Adapted from the online slides provided by John Zelle (
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
ALGORITHMS THIRD YEAR BANHA UNIVERSITY FACULTY OF COMPUTERS AND INFORMATIC Lecture two Dr. Hamdy M. Mousa.
Exception Handling Introduction Exception handling is a mechanism to handle exceptions. Exceptions are error like situations. It is difficult to decide.
Main task -write me a program
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Chapter 7 Decision Structures
Adapted from slides by Marie desJardins
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
Exceptions COMPSCI 105 S Principles of Computer Science.
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
Algorithmic Problem Solving CMSC 201 Adapted from slides by Marie desJardins (Spring 2015 Prof Chang version)
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
计算机科学概述 Introduction to Computer Science 陆嘉恒 中国人民大学 信息学院
Invitation to Computer Science, Java Version, Second Edition.
CS 127 Writing Simple Programs.  Stages involved  Analyze the problem  Understand as much as possible what is trying to be solved  Determine Specifications.
Chapter 2 - Algorithms and Design
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?
Dealing with Errors. Error Types Syntax Errors Runtime Errors Logical Errors.
Exceptions Handling Exceptionally Sticky Problems.
Conditions. Objectives  Understanding what altering the flow of control does on programs and being able to apply thee to design code  Look at why indentation.
1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the.
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
COP-3330: Object Oriented Programming Flow Control May 16, 2012 Eng. Hector M Lugo-Cordero, MS.
Topics: IF If statements Else clauses. IF Statement For the conditional expression, evaluating to True or False, the simple IF statement is if : x = 7.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
BACS 287 Programming Logic 2. BACS 287 Sequence Construct The sequence construct is the default execution mode for the CPU. The instructions are executed.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Programming Logic and Design, Introductory, Fourth Edition1 Understanding the Three Basic Structures Structure: a basic unit of programming logic Any program.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Algorithm Discovery and Design Objectives: Interpret pseudocode Write pseudocode, using the three types of operations: * sequential (steps in order written)
Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
Week 4 Program Control Structure
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Python Exceptions and bug handling Peter Wad Sackett.
Functions CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Head First Python: Ch 3. Files and Exceptions: Dealing with Errors Aug 26, 2013 Kyung-Bin Lim.
CS 101 – Oct. 7 Solving simple problems: create algorithm Structure of solution –Sequence of steps (1,2,3….) –Sometimes we need to make a choice –Sometimes.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Python Programming, 3/e1 Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures.
Python Boot Camp Booleans While loops If statements Else clauses
Line Continuation, Output Formatting, and Decision Structures
Lesson 04: Conditionals Topic: Introduction to Programming, Zybook Ch 3, P4E Ch 3. Slides on website.
Python: Control Structures
Python Programming: An Introduction to Computer Science
IF statements.
Midterm Exam 答題分布 Python Programming, 2/e.
Line Continuation, Output Formatting, and Decision Structures
Topics Introduction to File Input and Output
Lesson 04: Conditionals Class Chat: Attendance: Participation
Class 12.
ERRORS AND EXCEPTIONS Errors:
3. Decision Structures Rocky K. C. Chang 19 September 2018
15-110: Principles of Computing
Python Syntax Errors and Exceptions
Class 13 function example unstring if if else if elif else
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
By Ryan Christen Errors and Exceptions.
Jurassic Park Python Programming, 2/e.
Topics Introduction to File Input and Output
What is a Function? Takes one or more arguments, or perhaps none at all Performs an operation Returns one or more values, or perhaps none at all Similar.
Presentation transcript:

CS 127 Exceptions and Decision Structures

Exception Handling This concept was created to allow a programmer to write code that catches and deals with errors that arise when a program is running Exception handling says “Do these steps in my program, and if any problem crops up, handle it this way” Prevents a program from crashing and allows graceful recovery from unexpected input or situations

Exception Example import math def main(): print(“This program finds the real solutions to a quadratic”) try: a, b, c = eval(input(“Please enter the coefficients (a, b, c)”)) discRoot = math.sqrt(b * b - 4 * a *c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print(“\nThe solutions are:”,root1, root2) except ValueError: print(“\nNo real roots”)

Exception Handling If the statements execute without error, control passes to the next statement after the try….except If error occurs somewhere in the body, Python looks for an except clause with a matching error type If that suitable except is found, the handler code is executed In this way, the program does not crash

Exception Handling Single try statement can have multiple except clauses to catch various possible classes of errors Multiple excepts are similar to els ifs A bare except at the bottom acts as a catch all if none of the exceptions match the type of error that occurred try: #code goes here except NameError: #handle Invalid input specified except TypeError: #handle Invalid format (e.g. number was expected but string sent) except SyntaxError: #handle Invalid input (e.g. no comma placed between values in simultaneous assignment except: #handle something else that went wrong

Decision Structures Max of 3 If you are given 3 numbers, how would you find which number is the max def main(): x1, x2, x3 = eval(input(“Enter three numbers”)) #missing code here print(“The largest value is: “, max)

Approach 1 : Compare each to all if x1 >= x2 and x1 >=x3 max = x1 elif x2 >= x3 and x2 >=x1: max = x2 else : max=x3 Check each possible value against all other values to determine the largest How does this solution scale?? With 4 values or 5 values or 10 values?

Approach 2 : Decision Tree Start with a simple test of two values if x1 >= x2 If this holds true, then it breaks down to a choice between x1 and x3 Otherwise it is a choice between x2 and x3. The first decision “branches” into two possibilities, each of which is another decision, hence the name “decision tree”

Exercise Code the solution for the decision tree diagram below to determine the largest of three numbers

Approach 2 : Decision Tree The strength of this approach is efficiency No matter the ordering, comparisons will be made between two values and max will be assigned to the correct one How does this solution scale? What if we are asked to find the max of 5 numbers?

Approach 3 : Sequential Processing Assume the first number is the max Start iterating through the numbers and compare each one in turn If the new number is greater that the first, then set it as the new max Do this and continue till you check all numbers

Approach 3 : Sequential Processing Exercise Write the program for the Sequential Processing solution to this problem of finding the max of three numbers provided by a user Modify this solution to any amount of numbers, n

Approach 3 : Sequential Processing Is this algorithm the best? Does it scale well to larger problems? Is the sequencing easier to understand?

Takeaways There is always more than one way to solve a problem Take time to think about your solution to a problem and strive for clarity, simplicity, efficiency, scalability, and elegance Be general. Consider n numbers and solve for this rather than being specific (just assuming 3)

Exercise 1 Many companies pay time-and-a-half for hours worked above 40 in a given week. Write a program to input the number of hours worked and the hourly rate and calculate the total wages for the week

Exercise 2 The speeding ticket in a town is $50, plus $5 for each mph over the limit plus a penalty of $200 for any speed over 90 mph. Write a program that accepts the speed limit and a clocked speed and either prints a message indicating the speed was legal or prints the amount of the fine, if the speed is illegal