1 / 24

Decision Structures: Selection Statements

Decision Structures: Selection Statements. What Are Decision Structures?. Code tools which allow the program to perform different tasks for different conditions—in effect, the code “chooses” a set of actions when certain requirements are met.

caden
Download Presentation

Decision Structures: Selection Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Decision Structures: Selection Statements

  2. What Are Decision Structures? Code tools which allow the program to perform different tasks for different conditions—in effect, the code “chooses” a set of actions when certain requirements are met. Increases complexity and flexibility in the sequential execution of programs Part of a larger set of programming protocols known as Control Structures

  3. Temperature Example Input Celsius Convert to Fahrenheit Fahrenheit > 90? Condition yes Print heat warning Fahrenheit < 30? Condition yes Print cold warning

  4. Convert2.py # convert2.py # A program to convert Celsius temps to Fahrenheit. # This version issues heat and cold warnings. def main(): celsius = input("What is the Celsius temperature? ") fahrenheit = 9.0 / 5.0 * celsius + 32 print "The temperature is", fahrenheit, "degrees fahrenheit." if fahrenheit > 90: print "It's really hot out there, be careful!" if fahrenheit < 30: print "Brrrrr. Be sure to dress warmly" main()

  5. Relational Operators

  6. Boolean Data Types When an expression evaluates as true or false, we call it a Boolean statement. Python (like many languages) has a Boolean data type. Some languages interpret a true as 1 or -1 and a false as 0. In Python, a Boolean data type is called bool and is represented simply as True or False. >>> 3 * 4 < 3 + 4False

  7. A one-way decision structure • # quadratic2.py • # A program that computes the real roots of a quadratic equation. • # Bad version using a simple if to avoid program crash • import math • def main(): • print "This program finds the real solutions to a quadratic\n" • a, b, c = input("Please enter the coefficients (a, b, c): ") • discrim = b * b - 4 * a * c • if discrim >= 0: • discRoot = math.sqrt(discrim) • root1 = (-b + discRoot) / (2 * a) • root2 = (-b - discRoot) / (2 * a) • print "\nThe solutions are:", root1, root2 • main()

  8. Simple if Statements if radius >= 0 area = radius * radius * PI print "The area" “ for the circle of radius " + radius + “is " + area if booleanExpression statement(s)

  9. Two-way Decisions (If-Else) Using just the if keyword provides us with a single alternative and, implicitly, a second alternative—what to do if the if condition is NOT met. But this is not very clear or satisfactory as good programming. Python provides us with a structure that covers all exceptions to the condition linked with the if keyword. if <condition>: (note the colons; remember indentation) <statements>else: <statements>

  10. If..else with the quadratics program # quadratic3.py # A program that computes the real roots of a quadratic equation. # Illustrates use of a two-way decision import math def main(): print "This program finds the real solutions to a quadratic\n" a, b, c = input("Please enter the coefficients (a, b, c): ") discrim = b * b - 4 * a * c if discrim < 0: print "\nThe equation has no real roots!" else: discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print "\nThe solutions are:", root1, root2 main()

  11. Another if… else example # gpa_award.pyimport math def main(): print “This program determines student awards\n” GPA = float(input(“Enter the student’s GPA:”)) if GPA >= 3.8: print “Congratulations! You won the Mitchell scholarship!” else: print “Sorry. Your GPA does not qualify for an award.”main()

  12. Multiple Decisions (if… elif) Sometimes there are multiple choices, not just two. In these cases we want to “nest” if statements inside each other: 3.8 GPA and above gets the Mitchell scholarship But if you don’t qualify for that and still have a GPA of 3.5 or better, you get the Wilson award But if you have a GPA between 3.0 and 3.5, you may qualify for the Anderson Recognition Honorary Pocket Protector

  13. Example: GPAs and awards # gpa_award.pyimport math def main(): print “This program determines student awards\n” GPA = float(input(“Enter the student’s GPA:”)) if GPA >= 3.8: print “Congratulations! You won the Mitchell scholarship!”elif GPA >= 3.5 and GPA < 3.8 print “Congrats! You won the Wilson award!”elif GPA >= 3.0 and GPA < 3.5: print “OK, so you won the Anderson Honorary Pocket Protector.” else: print “Sorry. Your GPA does not qualify for an award.”main()

  14. Back to Quadratics… # quadratic4.py # A program that computes the real roots of a quadratic equation. # Illustrates use of a multi-way decision import math def main(): print "This program finds the real solutions to a quadratic\n" a, b, c = input("Please enter the coefficients (a, b, c): ") discrim = b * b - 4 * a * c if discrim < 0: print "\nThe equation has no real roots!" elif discrim == 0: root = -b / (2 * a) print "\nThere is a double root at", root else: discRoot = math.sqrt(b * b - 4 * a * c) root1 = (-b + discRoot) / (2 * a) root2 = (-b - discRoot) / (2 * a) print "\nThe solutions are:", root1, root2 main()

  15. Exception Handling A lot can go wrong with programs, mainly because either a) the programmer made a logical or syntax error b) the programmer didn’t give proper instructions to the user or c) the user is difficult or just stupid. When programmers can predict the kinds of errors that might arise from user input, she/he can write in ways of dealing with it—usually giving new instructions to the user. The program can “handle exceptions” or “handle errors.” Python provides a special syntax for exception handling. try: <statements>except <ErrorType>: <error handling statements>

  16. Handling Exceptions in the Quadratic program # quadratic5.py # A program that computes the real roots of a quadratic equation. # Illustrates exception handling to avoid crash on bad inputs import math def main(): print "This program finds the real solutions to a quadratic\n" try: a, b, c = 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" main()

  17. Exception Handling in the GPA example # gpa_award.pyimport math def main(): print “This program determines student awards\n”try: GPA = float(input(“Enter the student’s GPA:”)) if GPA >= 3.8: print “Congratulations! You won the Mitchell scholarship!” elif GPA >= 3.5 and GPA < 3.8 print “Congrats! You won the Wilson award!” elif GPA >= 3.0 and GPA < 3.5: print “OK, so you won the Anderson Honorary Pocket Protector.” else: print “Sorry. Your GPA does not qualify for an award.”except TypeError: print “You must enter a decimal point number.”main()

  18. The skeleton of maximum of 3 • def main(): n1, n2, n3 = input(“Enter three integers”) # code to determine max value print “The largest value is “, maxmain()

  19. Different decision strategies: the compound condition • Our task is to compare three numbers, and determine which is the largest. There are basically three different ways to do this. • First: The compound condition. • Python, unlike other languages, supports this syntax: if n1 >= n2 >= n3 max = n1

  20. Compound condition, cont. • if n1 >= n2 >= n3: max = n1elif n2 >= n1 and n2 >= n3: max = n2else: max = n3 • Plug this into the skeleton and try it.

  21. Decision tree: nested if else statements • if n1 >= n2: if n1 >= n3: max = n1 else: max = n3else: if n2 >= n3: max = n2 else: max = n3

  22. Sequential processing • Here’s an easy solution: set a max variable to the first number, and keep comparing it to every number. If some number is bigger than max, reset the value of max to that number, and keep comparing. • max = n1if n2 > max: max = n2if n3 > max: max = n3

  23. # maxn.py • # Finds the maximum of a series of numbers • def main(): • n = input("How many numbers are there? ") • # Set max to be the first value • max = input("Enter a number >> ") • # Now compare the n-1 successive values • for i in range(n-1): • x = input("Enter a number >> ") • if x > max: • max = x • print "The largest value is", max • main()

  24. Workshop • Create a command line program that simulates a Magic 8 Ball. You know what I mean: you shake the ball and get different answers. • To do this, you’ll need to generate random numbers between 0 and 9. Create a list from the strings below, and match the randomly generated integers to the index items in the string list. • The “answers” are: “Cannot predict now”, “Better not tell you now”, “It is certain”, “Ask again later”, “Yes”, “As I see it Yes”, “Don’t count on it”, “My source says No”, “Very doubtful”, “It is decidedly so”

More Related