Lecture 9 Decision Structures PartI
Lecture 9 Decision Structures PartI
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
main()
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
>>> 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?
<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()
print()
print("The solutions are: ", root1, root2)
def rootsQEq():
print("This program finds the real solutions to a quadratic.")
print()
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)
rootsQEq()
Next Lecture…
• Decision Structures- Part II