CS 111 - 3/7/17
Boolean Operators
Normally used to combine the results from a relational expression
to create a more complex condition
Traditionally there are 3 boolean operators
2 are binary operators (take 2 operands): or and
1 is a unary operator (takes 1 operand): not
For: and, or
Syntax:
and
or
For the and operator: if both and are true
then the result of the and operator is also true
otherwise the result of the and operator is false
Examaple: Is a value within a range of numbers
is x within the range from 10 to 20 (inclusive)
x = 35
if ( ( x >= 10 ) and ( x <= 20 ) ) :
print "The value is in the range from 10 to 20
For the or operator: if at least one of and
is true
then the result of the or operator is true
otherwise the result of the or operator is false
Truth Table: assume both x, y contain boolean (true/false) values
x y | x and y x or y | not x
==================================================
true true | true true | false
true false | false true | false
false true | false true | true
false false | false false | true
x = 3 T
y = 5 F T
z = 7 T F F
if ( ( ( x < 4 ) and ( y > 7 ) ) or ( not ( z < 4 ) ) ) :
print "expression is true"
else
print "expressin is false"
For not
Syntax:
not
For the not operator: if the is true
then the result of the not operator is false
otherwise the result of the not operator is true
Truth Table: assume x contain a boolean (true/false) value
x | not x
=====================
true | false
false | true
Python does have a short cut way to determine if a value
is with-in a range, the following code:
if ( ( x >= 10 ) and ( x <= 20 ) ) :
print "The value is in the range from 10 to 20
could be written as:
if ( 10 <= x <= 20 ) :
print "The value is in the range from 10 to 20
Edge Detection: Used in Computer Vision to highlight the
"important parts" of a picture