xiaojuan cai computational thinking 1 lecture 7 decision structure xiaojuan cai (蔡小娟)...
DESCRIPTION
Xiaojuan Cai Computational Thinking 3 Roadmap Decision structures if statement if-else statement if-elif-else statement Exception handling Algorithm design: Max of threeTRANSCRIPT
Xiaojuan Cai Computational Thinking 1
Lecture 7Decision Structure
Xiaojuan Cai(蔡小娟)[email protected]
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 7
if-statement• Syntax
• if <condition>:
<body>
• 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• <expr> <relop> <expr>
• <relop> is short for relational operatorPython Mathemati
csMeaning
< < 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__ = <modulename>, 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 b2-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 <condition>:
<statements>
else:
<statements>
• 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 b2-4ac<0 .
• if b2-4ac=0, we want to print only one root.• Three cases:
• b2-4ac<0
• b2-4ac=0
• b2-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 <condition1>: <case1 statements>elif <condition2>: <case2 statements>elif <condition3>: <case3 statements>…[else: <default statements>]
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:
<body>except <ErrorType1>[,<id1>]:
<handler1>except <ErrorType2>[,<id2>]:
<handler2>…[except:
<handler3>]
• The semantics: If an error occurs in the body, looks for a matching error type. If one is found, then [assign the exception to <id>, 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