Booleans Flashcards
What are booleans?
Booleans are operators that allow you to convey True or False statements.
We may need to know whether a certain condition has happened is True in order to execute the correct code. Show an example.
“Is my pool empty?”
if that is True then turn on the water to fill the pool
else, do nothing.
The parameter weekday is True if it is a weekday, and the parameter vacation is True if we are on vacation. We sleep in if it is not a weekday or we’re on vacation. Return True if we sleep in.
def sleep_in(weekday, vacation):
def sleep_in(weekday, vacation:
if not weekday or vacation:
return True
else:
return False
We have two monkeys, a and b, and the parameters a_smile and b_smile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return True if we are in trouble.
def monkey_trouble(a_smile, b_smile):
def monkey_trouble(a_smile, b_smile):
if a_smile and b_smile:
return True
if not a_smile and not b_smile:
return True
else:
return False
We have a loud talking parrot. The “hour” parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return True if we are in trouble.
def parrot_trouble(talking, hour):
–Use # to comment solution
def parrot_trouble(talking, hour):
return (talking and (hour < 7 or hour > 20))
# Need extra parenthesis around the or clause
# since and binds more tightly than or.
# and is like arithmetic *, or is like arithmetic +
1 > 2
False
1 == 1
True
What is the operator == ?
if two values of two operands are equal, then the condition becomes true.
What is the operator != ?
if the values of two operands are not equal, then condition becomes true
What is the operator > ?
if the value of the left operand is greater than the value of the right operand, then condition becomes true.
What is the operator < ?
if the left operand is less than the value of the right operand, then the condition beecomes true.
What is the operand >= ?
if the value of the left operand is greater than or equal to the value of the right operand, then condition becomes true
What is the operand <= ?
if the value of the left operand is less than or equal to the value of the right operand, then condition becomes true.
a = 3
b = 4
return (a == b)
false
a = 3
b = 4
return (a !=b)
True