Slides

advertisement
Selection
Victor Norman
CS104
Calvin College
Reading Quiz
• Counts toward your grade.
New type: bool
• Stands for Boolean (named after George
Boole)
• Two values: True and False
• Operations:
– and, or, not
– equality (==), inequality (!=)
Booleans necessary for “testing”
• You “constantly” are making decision:
– if something is true, I’ll do this, otherwise, I’ll do that.
– Code is similar.
• if something < somethingelse:
– something < somethingelse is a boolean expression:
produces True or False.
• if something == 0:
– True if something evaluates to the value 0, False
otherwise.
• Can be used in assignments:
– witch = (weight(she) == weight(duck)) # witch has value
True or False.
Boolean operators
•
•
•
•
<val> < <val>
<val> > <val>
etc: <, >, <=, >=, ==, !=
These are boolean expressions: when evaluated
they produce True or False.
Logical Operators:
• <booleanExpr> and <booleanExpr>
• <booleanExpr> or <booleanExpr>
• not <booleanExpr>
Clicker Questions
if Statement Syntax
if <boolean expression>:
<statements: executed if expr is True>
if <boolean expression>:
<statements: executed if expr is True>
else:
<statements: executed if expr is False>
Chained Conditionals
if <booleanExpression1>:
<statements: executed if expr is True>
elif <booleanExpression2>:
<statements: executed if expr1 is False and
expr2 is True>
elif <boolExpr3>:
<statements…>
else: # optional!
<statements>
Example of use
Suppose you have a function called
turnDegrees(deg) which takes a positive or
negative value in deg. You want to turnLeft() if
deg is positive, turnRight() if negative, and do
nothing if 0. How would you write this code?
def turnDegrees(deg):
if deg > 0:
turnLeft(deg)
elif deg < 0:
turnRight(-1 * deg)
Nested conditional
Q: Write code that prints the word “odd” or
“even” depending on the value of variable
anInt, and also prints “greater than 10” if the
odd number has a value greater than 10.
A: if anInt % 2 == 0 :
print("even”)
else:
print("odd”)
if anInt > 10:
print("greater than 10”)
Clicker Question
if temperature > 0:
print("above freezing")
elif temperature == 0:
print("at freezing")
else:
print("below freezing")
Does the code below do exactly the same thing as the code above?
(Assume temperature already refers to some numeric value.)
if temperature > 0:
print("above freezing")
elif temperature == 0:
print("at freezing")
elif temperature < 0:
print("below freezing")
Clicker Question
age
| experience: 0 | 1-2
| 3+
------------------------------------------------under 18
|
$6.50 | $9.50 | $11.00
18 and over
|
$6.50 | $12.00 | $12.00
if experience == 0:
wage = 6.5
elif (1) :
if (2) :
wage = 9.5
else:
wage = 11
else:
wage = 12
Assignment
• Do ~60 questions in CodeLab.
• Very good practice!
Download