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

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 (
Selection (decision) control structure Learning objective
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Chapter 4 Making Decisions
C++ for Engineers and Scientists Third Edition
Intro to Robots Conditionals and Recursion. Intro to Robots Modulus Two integer division operators - / and %. When dividing an integer by an integer we.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Chapter 7 Decision Structures
Exceptions COMPSCI 105 S Principles of Computer Science.
The University of Texas – Pan American
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Algorithmic Problem Solving CMSC 201 Adapted from slides by Marie desJardins (Spring 2015 Prof Chang version)
Invitation to Computer Science, Java Version, Second Edition.
Decision Structures and Boolean Logic
Announcements 1st homework is due on July 16, next Wednesday, at 19:00 Submit to SUCourse About the homework: Add the following at the end of your code.
CHAPTER 4: CONDITIONAL STRUCTURES Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
Flow of Control Part 1: Selection
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 4 Decision.
Computer Science 111 Fundamentals of Programming I Making Choices with if Statements.
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 5: Introduction to C: More Control Flow.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
Python Conditionals chapter 5
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Chapter Making Decisions 4. Relational Operators 4.1.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Xiaojuan Cai Computational Thinking 1 Lecture 8 Loop Structure Xiaojuan Cai (蔡小娟) Fall, 2015.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Xiaojuan Cai Computational Thinking 1 Lecture 2 Simple Programs Xiaojuan Cai (蔡小娟) Fall, 2015.
8. DECISION STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
CS 127 Exceptions and Decision Structures. Exception Handling This concept was created to allow a programmer to write code that catches and deals with.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Today… Operators, Cont. Operator Precedence Conditional Statement Syntax. Winter 2016CISC101 - Prof. McLeod1.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Python Programming, 3/e1 Python Programming: An Introduction to Computer Science Chapter 7 Decision Structures.
Python Review 1.
Exceptions in Python Error Handling.
Making Choices with if Statements
Lesson 04: Conditionals Topic: Introduction to Programming, Zybook Ch 3, P4E Ch 3. Slides on website.
Python Programming: An Introduction to Computer Science
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Selection CIS 40 – Introduction to Programming in Python
Lesson 04: Conditionals Class Chat: Attendance: Participation
Class 12.
3. Decision Structures Rocky K. C. Chang 19 September 2018
15-110: Principles of Computing
Class 13 function example unstring if if else if elif else
CHAPTER 5: Control Flow Tools (if statement)
Control 9 / 25 / 19.
Presentation transcript:

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

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

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

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.

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

Xiaojuan Cai Computational Thinking 6 The flow chart

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.

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

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.

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__’

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!

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

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.

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

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

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

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.

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

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

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.

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 …

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

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

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.

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?

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

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

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

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

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)

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!

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

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