Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with."— Presentation transcript:

1 CS 127 Exceptions and Decision Structures

2 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

3 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”)

4 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

5 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

6 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)

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

8 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”

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

10 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?

11 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

12 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

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

14 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)

15 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

16 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


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

Similar presentations


Ads by Google