Digression: Scoring Matrices
Lecture 7
Decisions
L7 Decisions – 2
Objectives of this Lecture
• A little revision
• To understand the conditional (decision) statement
– if
– if-else
• Comparison operators
• Logical operators
L7 Decisions – 3
Revision: Accumulator Algorithm
The general form of an accumulator algorithm looks like:
– Initialize the accumulator variable
– Perform computation
(e.g. in case of factorial multiply by the next smaller number)
– Update accumulator variable
– Loop until final result is reached
(e.g. in case of factorial the next smaller number is 1)
– Output accumulator variable
This is called a Pattern, or Software Design Pattern. That is,
a recurring, reusable generalised set of instructions
L7 Decisions – 4
Decision making
L7 Decisions – 5
Decision Structures
• So far, we’ve viewed programs
as sequences of instructions
that are followed one after the
other.
• While this is a fundamental
programming concept, it is not
sufficient in itself to solve every
problem.
• We need to be able to alter the
sequential flow of a program to
suit a particular situation.
L7 Decisions – 6
Don’t forget the “:”• if
• The condition is a Boolean expression, i.e. evaluates
to values True or False
• The condition statement is evaluated;
– If it evaluates to True, the (indented) statements
in the body are executed;
– Otherwise, execution proceeds to next statement
Simple if statements
L7 Decisions – 7
Simple if statements
L7 Decisions – 8
Boolean Expressions – Comparisons
• What does a Boolean expression, i.e. condition, look
like?
• At this point, let’s use simple comparisons.
–
operator
L7 Decisions – 9
Comparison operators
Note ==
L7 Decisions – 10
Comparison Operators
>>> 8 < 10 True >>> 8 > 10
False
• Notice the use of == for equality. Since Python uses
= to indicate assignment, a different symbol is
required for the concept of equality.
• A common mistake is using = in comparisons!
>>> 8 == 10
False
L7 Decisions – 11
Forming Comparisons
• When comparing strings, the ordering is
lexicographic, meaning that the strings are sorted
based on the underlying Unicode.
– Unicode (and before that, ASCII) is a way of
representing characters as integers
– Because of this, all upper-case Latin letters come
before lower-case letters. (“Bbbb” comes before
“aaaa”)
>>> “Hello” < "hello" True L7 Decisions - 12 Logical/Boolean operators Logical operators are used to combine comparisons L7 Decisions - 13 Logical operator : and • The and of two Boolean expressions is True exactly when both of the Boolean expressions are True. • We can represent this in a truth table. • P and Q represents Boolean expressions. • Since each Boolean expression has two possible values, there are four possible combinations of values. P Q P and Q T T T T F F F T F F F F L7 Decisions - 14 Logical operator : or • The or of two Boolean expressions is True when either Boolean expression is true. • The only time or is false is when both Boolean expressions are False. • Also, note that or is True when both Boolean expressions are True. P Q P or Q T T T T F T F T T F F F L7 Decisions - 15 Logical operator : not • The not operator computes the opposite of a Boolean expression. • not is a unary operator, meaning it operates on a single Boolean expression. • We can put these operators together to make arbitrarily complex Boolean expressions. • The interpretation of the expressions relies on the precedence rules for the operators. P not P T F F T L7 Decisions - 16 Example: Temperature Warnings Design Input: A value representing a Celsius temperature Process: (None) Output: If temperature greater than 40 print warning If temperature less than 1 print warning L7 Decisions - 17 >>> def stayhome():
temp = float(input(“What is the temperature today? “))
if temp >= 40:
print(“The temperature is too high”)
print(“Stay at home”)
if temp <= 0 : print(“The temperature is too low”) print(“Stay at home") print("Have a good day”) >>> stayhome()
What is the temperature today? 42
The temperature is too high
Stay at home
Have a good day
Simple if statements: Example
What happens for 36?
L7 Decisions – 18
>>> def stayhome():
temp = float(input(“What is the temperature today? “))
if temp >= 40 or temp <= 0: print(“The temperature is not appropriate”) print(“Stay at home") print("Have a good day”) >>> stayhome()
What is the temperature today? 36
Have a good day
Simple if statements: Example
L7 Decisions – 19
Quadratic Equation Example
Consider the quadratic equation program.
# quadratic.py
# A program that computes the real roots of a quadratic equation.
# Note: This program crashes if the equation has no real roots.
import math # Makes the math library available.
def main():
print(“This program finds the real solutions to a quadratic\n”)
a = float(input(“Enter coefficient a: “))
b = float(input(“Enter coefficient b: “))
c = float(input(“Enter coefficient 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)
What does \n do?
L7 Decisions – 20
Using the Math Library
Running the program
>>> main()
This program finds the real solutions to a quadratic
Please enter coefficient a: 3
Please enter coefficient b: 4
Please enter coefficient c: -1
The solutions are: 0.215250437022 -1.54858377035
L7 Decisions – 21
Decisions
Noting the comment, when b2-4ac < 0, the program
crashes.
>>> main()
This program finds the real solutions to a quadratic
Please enter coefficient a: 1
Please enter coefficient a: 2
Please enter coefficient a: 3
Traceback (most recent call last):
File “quadratic_roots.py”, line 21, in
main()
File “quadratic_roots.py”, line 15, in main
discRoot = math.sqrt(b * b – 4 * a * c)
ValueError: math domain error
L7 Decisions – 22
Decisions
We can check for this situation. Here’s our first attempt.
# 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 = float(input(“Enter coefficient a: “))
b = float(input(“Enter coefficient b: “))
c = float(input(“Enter coefficient 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)
L7 Decisions – 23
Two-Way Decisions
• We first calculate the discriminant (b2-4ac) and then
check to make sure it’s non-negative. If it is, the
program proceeds and we calculate the roots.
• Look carefully at the program.
– What’s wrong with it?
– Hint: What happens when there are no real roots?
L7 Decisions – 24
Two-Way Decisions
This program finds the real solutions to a quadratic
Enter coefficient a: 1
Enter coefficient b: 1
Enter coefficient c: 1
>>>
• This is worse than the version that crashes, because we
don’t know what went wrong!
– Don’t even know that there is a problem
L7 Decisions – 25
Two-Way Decisions
• We could add another if after first if:
if discrim < 0:
print("The equation has no real roots!" )
• This works, but feels wrong. We have two decisions, with
mutually exclusive outcomes
– if discrim >= 0 then discrim < 0 must be false,
and vice versa.
L7 Decisions - 26
Two-Way Decisions
L7 Decisions - 27
Two-Way Decisions
• In Python, a two-way decision can be implemented
by attaching an else clause onto an if clause.
• This is called an if-else statement:
if
else:
L7 Decisions – 28
Two-Way Decisions
• When Python encounters if-else structure, it first
evaluates the condition. If the condition evaluates to
True, the statements under the if are executed.
• If the condition evaluates to False, the statements
under the else are executed.
• In either case, the statement following the if-else
structure is then executed
L7 Decisions – 29
Two-Way Decisions
# 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 = float(input(“Enter coefficient a: “))
b = float(input(“Enter coefficient b: “))
c = float(input(“Enter coefficient 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 ) L7 Decisions - 30 Two-Way Decisions This program finds the real solutions to a quadratic Enter coefficient a: 1 Enter coefficient b: 1 Enter coefficient c: 2 The equation has no real roots! >>>
This program finds the real solutions to a quadratic
Enter coefficient a: 2
Enter coefficient b: 5
Enter coefficient c: 2
The solutions are: -0.5 -2.0
L7 Decisions – 31
Lecture Summary
• We learned about decision making in computer
program
• We learned about boolean expressions and their use
in if and if-else decision statements.
• We learned about Logical and Comparison operators
Lecture 7�Decisions
Objectives of this Lecture
Revision: Accumulator Algorithm
Decision making
Decision Structures
Simple if statements
Simple if statements
Boolean Expressions – Comparisons
Comparison operators
Comparison Operators
Forming Comparisons
Logical/Boolean operators
Logical operator : and
Logical operator : or
Logical operator : not
Example: Temperature Warnings
Simple if statements: Example
Simple if statements: Example
Quadratic Equation Example
Using the Math Library
Decisions
Decisions
Two-Way Decisions
Two-Way Decisions
Two-Way Decisions
Two-Way Decisions
Two-Way Decisions
Two-Way Decisions
Two-Way Decisions
Two-Way Decisions
Lecture Summary