CS 149
Professor: Alvin Chao
What kind of soup is made with 1’s and 0’s?� Beef Boolean
Next week:�Tues 11pm Week 3 Reading
Wed 11pm HW3
Thu Actual Quiz 1
Fri 11pm Lab 6
Boolean Expressions
Relational Operators
Comparison Operators
Comparison Operators - are used to compare two values:
and Returns True if both statements are true
�or Returns True if one of the statements is true
�not Reverse the result, returns False if the result is true�
Boolean Expressions
Model 1 Relational Ops
Interactions | Value displayed | Relational Operator |
three = 3 | none | none |
four = 4 | none | none |
print(four) | 4 | none |
three > four | False | > |
is_larger = three > four | | |
print(is_larger) | | |
three == four | | |
three < four | | |
three <= four | | |
three = four | | |
three == four | | |
Equality comparison
three = 3
trey = 3
three_point = 3.0
three_str = “3”
What do these evaluate to?
three == trey
three == three_point
three_point == three_point
three == three_str��.1 + .2 == .3
If Statements
if(boolean_expression):� Statement or block
else:
Statement or block
if(performance > 80):
bonus_pay += 1000���if(performance > 80):
bonus_pay +=1000�else:
print(“You’re fired.”)
If examples
x = 10
hat = "fez"
if x > 100 or hat == "fez":
print("A")
if x < 50:
print("B")
else:
print("C")
else:
print("D")
if hat == "fedora":
print("E")
print("F")
x = 10
if x < 100:
print("A")
elif x < 50:
print("B")
else:
print("C")
print("D")
Danger…
if(performance > 80):
print(“Nice work”)
bonus_pay += 1000
Prevention
We indent the second line to make it a part of the if block
if(performance > 80):
print(“Nice work”)
bonus_pay += 1000
To prevent the mistake from the previous slide
Empty Blocks = bad style
# A if (performance <= 80): pass else: bonus_pay += 1000 | # B�if (performance > 80): bonus_pay += 1000 | # C�if (performance > 80): bonus_pay += 1000 else:� pass |
Conditionals
Boolean expressions may also use conditional operators to implement basic logic. Relational operators are always executed first so usually no need for parentheses��Operators: not, and , or��
If all 3 operators appear in the same expression, Python will evaluate the not first the and and finally or. If there are multiples of the same operator they are evaluated from left to right.��EXAMPLE VARIABLES EXAMPLE EXPRESSIONS
a = 3 a < b and funny�b = 4 a < b and b < c�c = 5 funny and a < c�funny = True not funny or weird�weird = False���
Parts of this activity are based on materials developed by Chris Mayfield and Nathan Sprague.
</end>