0% found this document useful (0 votes)
28 views

Lecture 9 Decision Structures PartI

The document discusses decision structures in programming, which allow altering a program's sequential flow based on different conditions. It covers one-way decisions using if statements and two-way decisions adding else clauses. Examples demonstrate comparing values, using relational, logical, membership and identity operators to form conditions. Chaining comparisons and combining operators are also illustrated. The document aims to enhance understanding of conditional control flow in programs.

Uploaded by

thezynkofficial
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Lecture 9 Decision Structures PartI

The document discusses decision structures in programming, which allow altering a program's sequential flow based on different conditions. It covers one-way decisions using if statements and two-way decisions adding else clauses. Examples demonstrate comparing values, using relational, logical, membership and identity operators to form conditions. Chaining comparisons and combining operators are also illustrated. The document aims to enhance understanding of conditional control flow in programs.

Uploaded by

thezynkofficial
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Principles of Programming

languages
Decision Structures- Part I
Lecture 9
Today…
• Last Session:
• Functions- Part II

• Today’s Session:
• Decision Structures- Part I:
• One- and Two-way Decisions
• Booleans
• Relational, Logical, Membership, and Identity Operators
Decision Structures
• So far, we have mostly viewed computer programs as sequences of
instructions that are interpreted one after the other

• Sequencing is a fundamental concept of programming, but alone it is not


sufficient to solve every problem

• Often it is necessary to alter the sequential flow of a program to suit the


needs of a particular situation

• We will study decision structures, which are statements that allow a


program to execute different sequences of instructions for different cases
Example: Temperature Warnings
• Let us consider again our Celsius to Fahrenheit temperature program
def main():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees Fahrenheit")

main()

• How can we enhance this program to print a suitable warning when


the temperature is extreme (say, over 90 degrees F, it deserves a heat
warning, and under 30 it deserves a cold warning)?
Example: Temperature Warnings
• Enhanced Celsius to Fahrenheit temperature program

def main():
celsius = eval(input("What is the Celsius temperature? "))
fahrenheit = 9/5 * celsius + 32
print("The temperature is", fahrenheit, "degrees Fahrenheit")
if fahrenheit > 90:
print(“It is really hot outside. Be careful!”)
if fahrenehit < 30:
print(“Brrrrr. Be sure to dress warmly!”)

main()
One-Way Decisions
• We applied the Python if statement to implement a one-way decision,
using the following form: One-way Condition

if <condition>: <condition> Yes


true?
<body>
No
• <body> is just a sequence of one or more statements
<statement>
indented under the if heading
<statement>

• Simple <condition> compares values of two expressions


<statement>
using a comparison operator as follows:
<expr> <comp> <expr>
Comparison Operators
• There are six comparison (or relational) operators in Python
Python Mathematics Meaning
< < Less than
<= ≤ Less than or equal to
== = Equal to
>= ≥ Greater than or equal to
> > Greater than
!= ≠ Not equal to
If Statement
sandwich_order = “Ham Roll”
If sandwitch_order==“Ham Roll”
print(“Price:$1.75”)
Conditions and Booleans
• Conditions may compare either numbers or strings

• Strings are compared lexicographically, meaning that they are


compared character by character according to their Unicode values
• E.g., “Bbbb” is less than “aaaa” since “B” precedes “a” (all uppercase Latin
letters come before lowercase equivalents)

• A condition is actually a Boolean expression, which produces a value of


either True (the condition holds) or False (the condition does not hold)
Conditions and Booleans
• Here are few interactive examples:
>>> "a" < "b" >>> "a" == "a"
True True
>>> "aa" < "a" >>> type("a" == "a")
False <class 'bool'>
>>> "a" < "A" >>> 3 < 4
False True
>>> "Hello" < "hello" >>> 3 * 4 < 3 + 4
True False
>>> >>>
Chaining Comparison Operators
• Comparison operators can be chained
>>> 1 < 2 < 3 >>> 3 < x < 2
True False
>>> x = 2 >>> 2 == x < 4
>>> 1 < x < 2 True
False >>> y = 4
>>> 1 < x < 2 < 3 < 4 < 5 >>> 1 < x <= 2 < y
False True
>>> 1 < x <= 2 >> 1 != 2
True True
Logical Operators
• We can also use logical operators with our conditions
Operator Description
not x Evaluates to the opposite- i.e., if x is False, the result
will be True and vice versa

x and y Evaluates to True if both, x and y are True


x or y Evaluates to True if either x is True or y is True
Logical Operators
• True or False?
Statement Result
(3*4 > 10) and (3+4 < 10) True
(3*4 < 10) or (3+4 < 10) True
not ((3*4 < 10) or (3+4 < 10)) False
(3 * 4 > 10) or (5 + 5 > 10) and (4 * 4 > 15) or True
(5 + 4 > 10)
Membership Operators
• We can also use membership operators with conditions
Operator Description
x in sequence Evaluates to True if x is found in the given sequence
(e.g., string)

x not in Evaluates to True if x is NOT found in the given


sequence sequence (e.g., string)
Membership Operators
• True or False?
Statement Result
“15-110” in “15-110 is a lot of fun!” True
“Java” not in “15-110 uses Python to illustrate True
computing principles”
1 in “15-110” ERROR
“1” in “15-110” True
Identity Operators
• We can also use identity operators with conditions
Operator Description
x is y Evaluates to True if x and y point to the same object

x is not y Evaluates to True if x and y do not point to the same object


Membership Operators
• True or False?

>>> x = "cmu"
>>> y = "cmu"
>>> x is y
True
>>> z = x
>>> z is y
True
>>>
Membership Operators
• True or False?

>>> x = "cmu"
>>> y = "cmu"
>>> x is y
True
>>> z = x
>>> z is y
True
>>>
Membership Operators
• True or False?

>>> x = "cmu" >>> a = 5


>>> y = "cmu" >>> if (type(a) is int):
>>> x is y ... print("true")
True ... else:
>>> z = x ... print("false")
>>> z is y ...
True true
>>> >>>
Membership Operators
• True or False?

>>> x = "cmu" >>> a = 5 >>> b = 5.4


>>> y = "cmu" >>> if (type(a) is int): >>> if (type(b) is not int):
>>> x is y ... print("true") ... print("true")
True ... else: ... else:
>>> z = x ... print("false") ... print("false")
>>> z is y ... ...
True true true
>>> >>> >>>
Membership Operators
• True or False?

>>> x = "cmu" >>> a = 5 >>> b = 5.4


>>> y = "cmu" >>> if (type(a) is int): >>> if (type(b) is not int):
>>> x is y ... print("true") ... print("true")
True ... else: ... else:
>>> z = x ... print("false") ... print("false")
>>> z is y ... ...
True true true
>>> >>> >>>
Two-Way Decisions
• Notice how we attached an else clause onto an if clause to come up
with what we refer to as a two-way decision
No <condition> Yes
true?
if <condition>:
<statements>
else: <statement> <statement>
<statements>
<statement> <statement>

<statement> <statement>
If else
• An if else python statement evaluates whether an expression is true
or false.
• If a condition is true, the “if” statement executes otherwise the “else”
statement executes.
• When you are writing a program, you may want a block of code to run
only when a certain condition is met.
• Condition statements allow you to control the flow of your program
more effectively.
If else
Fees = 2000
If fees > 500:
print(“register”)
else:
print(“Do not register”)
Revisiting Our Quadratic Equation Solver
#The following line will make the math library in Python available for us.
import math

def rootsQEq():
print("This program finds the real solutions to a quadratic.")
print()

a = eval(input("Enter the value of coefficient a: "))


b = eval(input("Enter the value of coefficient b: "))
c = eval(input("Enter the value of coefficient c: "))
Revisiting Our Quadratic Equation Solver
#To call a function from the math library, we can use the
#dot operator as follows:
s_root_val = math.sqrt(b*b - 4 * a * c)
root1 = (-b + s_root_val)/(2*a)
root2 = (-b - s_root_val)/(2*a)

print()
print("The solutions are: ", root1, root2)

#Call the function rootsQEq()


rootsQEq()
Revisiting Our Quadratic Equation Solver
• A sample run:
This program finds the real solutions to a quadratic.

Enter the value of coefficient a: 1 What is the


Enter the value of coefficient b: 2 problem?
Enter the value of coefficient c: 3
Revisiting Our Quadratic Equation Solver
• The problem is that
• The sqrt function is unable to compute the square root of a
negative number

• How can we avoid this problem?


• We can first compute the discriminant
• Then, we can check if it is negative (via using the ifstatement)
• If it is negative, we can print out that the equation has no real roots
• Otherwise (via using the elseclause), we can compute the solutions and
print them out
A Refined Quadratic Equation Solver
import math

def rootsQEq():
print("This program finds the real solutions to a quadratic.")
print()

a = eval(input("Enter the value of coefficient a: "))


b = eval(input("Enter the value of coefficient b: "))
c = eval(input("Enter the value of coefficient c: "))

discriminant = b * b – 4 * a * c
A Refined Quadratic Equation Solver
if discriminant < 0:
print(“The equation has no real roots!”)
else:
s_root_val = math.sqrt(discriminant)
root1 = (-b + s_root_val)/(2*a)
root2 = (-b - s_root_val)/(2*a)

print(“\nThe solutions are: ", root1, root2)

rootsQEq()
Next Lecture…
• Decision Structures- Part II

You might also like