Presentation is loading. Please wait.

Presentation is loading. Please wait.

Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) Fall, 2015.

Similar presentations


Presentation on theme: "Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) Fall, 2015."— Presentation transcript:

1 Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) cxj@sjtu.edu.cn Fall, 2015

2 Xiaojuan Cai Computational Thinking 2 Objective To understand the decision structures: simple decision: if statement two-way decision: if-else statement multi-way decision: if-elif-else statement To understand the idea of exceptions To know the bool data type Algorithm design: decision structure

3 Xiaojuan Cai Computational Thinking 3 Roadmap Decision structures if statement if-else statement if-elif-else statement Exception handling Algorithm design: Max of three

4 Xiaojuan Cai Computational Thinking 4 The control flow graph So far, programs are executed as sequences. Control structures allow us to alter this sequential program flow. Decision structures are statements that allow a program to execute different sequences of instructions for different cases.

5 Xiaojuan Cai Computational Thinking 5 Example: temperature warning Susan 在温度转换程序中希望加入一个警告, 当温度超过 90 华氏度或低于 30 华氏度的时 候发出警告,避免外出。 If fahrenheit > 90 print a heat warning If fahrenheit < 30 print a cold warning Convert2.py

6 Xiaojuan Cai Computational Thinking 6 The flow chart

7 Xiaojuan Cai Computational Thinking 7 if -statement Syntax if : Semantics First, the condition in the heading is evaluated. If the condition is true, the body is executed, and then the next statement. If the condition is false, the body are skipped.

8 Xiaojuan Cai Computational Thinking 8 Conditions is short for relational operator PythonMathematicsMeaning <<Less than <=≤Less than or equal to ===Equal to >=≥Greater than or equal to >>Greater than !=≠Not equal to

9 Xiaojuan Cai Computational Thinking 9 Boolean expressions Notice the use of == for equality. A common mistake is using = in conditions! The ordering of string is lexigraphic: ( “ Bbbb ” < “ aaaa ”) Conditions are of type bool with values True and False, named for the English mathematician George Boole.

10 Xiaojuan Cai Computational Thinking 10 Example: Conditional program execution Some modules are designed to be run directly (programs or scripts). Others are made to be imported (libraries). We want to create a hybrid: a stand-alone program and as a library. When the program is imported: __name__ =, otherwise __name__ = ‘__main__’

11 Xiaojuan Cai Computational Thinking 11 Example: Conditional program execution If a module is imported, __name__ is the name of the module. When a file is run directly, __name__ is the value ‘__main__’. We can change the final lines of our programs to: if __name__ == '__main__': main() Virtually every Python module ends this way!

12 Xiaojuan Cai Computational Thinking 12 Roadmap Decision structures if statement if-else statement if-elif-else statement Exception handling Algorithm design: Max of three

13 Xiaojuan Cai Computational Thinking 13 Two-way decisions Review the quadratic program: the case of b 2 -4ac<0. Previously, just crash – ValueError Use simple decision, nothing happened Another if ? Could be, but there is better one: if-else statement.

14 Xiaojuan Cai Computational Thinking 14 if : else: Semantics First, the condition in the heading is evaluated. If the condition is true, the body under if is executed, and then pass the control to the next statement. If the condition is false, the body under else is executed, and then pass the control to next statement. if-else statement

15 Xiaojuan Cai Computational Thinking 15 Roadmap Decision structures if statement if-else statement if-elif-else statement Exception handling Algorithm design: Max of three

16 Xiaojuan Cai Computational Thinking 16 Multi-way decision Review the quadratic program: the case of b 2 -4ac<0. if b 2 -4ac=0, we want to print only one root. Three cases: b 2 -4ac<0 b 2 -4ac=0 b 2 -4ac>0

17 Xiaojuan Cai Computational Thinking 17 if-elif-else statement Multi-way decision can be implemented by using nested if-else. However, if-elif-else is a better choice. if : elif : elif : … [else: ] else part is optional.

18 Xiaojuan Cai Computational Thinking 18 Roadmap Decision structures if statement if-else statement if-elif-else statement Exception handling Algorithm design: Max of three

19 Xiaojuan Cai Computational Thinking 19 Exception handling Decision structures are used to protect against rare but possible errors. Sometimes the algorithm becomes hard to follow due to so many checks. Exception: a mechanism to solve this design problem. Informally, “ Do these steps, and if any problem crops up, handle it this way. ”

20 Xiaojuan Cai Computational Thinking 20 Exception handling The try-except statement try: except [, ]: except [, ]: … [except: ] The semantics: If an error occurs in the body, looks for a matching error type. If one is found, then [assign the exception to, and] the handler code is executed. except part is optional. Without this statement, the program will crash if none is match.

21 Xiaojuan Cai Computational Thinking 21 Exceptions ValueError: e.g., performing sqrt to a negative number NameError: the number of params are wrong TypeError: operator and operands not match SyntaxError: ZeroDivisionError: divided by zero …

22 Xiaojuan Cai Computational Thinking 22 Roadmap Decision structures if statement if-else statement if-elif-else statement Exception handling Algorithm design: Max of three

23 Xiaojuan Cai Computational Thinking 23 Study in design: Max3 Problem: max of three numbers Input: three numbers Output: the maximum one def main(): x1, x2, x3 = input("Please enter three values: ") # sets max to the value of the largest print "The largest value is", max

24 Xiaojuan Cai Computational Thinking 24 Algo 1: three-way decision if x1 >= x2 >= x3: max = x1 Python does allow this statement. (most languges do not.) Bad design, you need 3! cases.

25 Xiaojuan Cai Computational Thinking 25 Algo 1: three-way decision if x1 >= x2 and x1 >= x3: max = x1 elif x2 >= x1 and x2 >= x3: max = x2 elif x3 >= x1 and x3 >= x2: max = x3 Better, perform 3*(3-1) compares in worst case. Can we do better?

26 Xiaojuan Cai Computational Thinking 26 Algo 2: decision tree Worst case: 3-1 comparisons Optimal solution, but difficult to implement

27 Xiaojuan Cai Computational Thinking 27 Algo 2: decision tree if x1 >= x2: if x1 >= x3: max = x1 else: max = x3 else: if x2 >= x3: max = x2 else max = x3

28 Xiaojuan Cai Computational Thinking 28 Algo 3: sequencial How would you solve this problem? Sequential processing Initially max = x1 Always compare max with xi, and update max Return max Worst case: 3-1 comparisons, optimal

29 Xiaojuan Cai Computational Thinking 29 Algo 3: sequencial Easy to implement and easy to expand to n-numbers: max = x1 if x2 > max: max = x2 if x3 > max: max = x3

30 Xiaojuan Cai Computational Thinking 30 Alternative: built-in function Python has a built-in function called max that returns the largest of its parameters. def main(): x1, x2, x3 = input("Please enter three values: ") print "The largest value is", max(x1, x2, x3)

31 Xiaojuan Cai Computational Thinking 31 Lessons There ’ s usually more than one way. Find a correct algorithm. Then strive for better one: clarity, simplicity, efficiency, scalability, and elegance. Generality is good. If the max of n is as easy to write as the max of three, write the more general program. Don’t reinvent the wheel. find out if there’s already a solution!

32 Xiaojuan Cai Computational Thinking 32 Conclusion Decision structures allow a program to execute different sequences. if, if-else, if-elif-else statements Boolean expressions:, >=, ==, != Bool type: True, False Exception handling makes programs more “bulletproof”. Algorithm design: correct, efficient, and understandable

33 Xiaojuan Cai Computational Thinking 33 Homework Textbook: Chapter 3 [Zelle]: True/False Multiple choice


Download ppt "Xiaojuan Cai Computational Thinking 1 Lecture 7 Decision Structure Xiaojuan Cai (蔡小娟) Fall, 2015."

Similar presentations


Ads by Google