Section 2.20 Boolean Truthiness
Subgoals for evaluating an assignment statement.
-
Decide order of operations
- Decompose as necessary
-
Determine operator behavior based on operands
- Operator and operands must be compatible
-
Solve arithmetic, expression, or operation
- Decompose as necessary
Subsection 2.20.1
Given the following code snippet, evaluate the final statement (the last line). If invalid, give the reason. If valid, what value is assigned to the variable?
alpha = 0
beta = 1
gamma = 5
result = alpha > beta or gamma
Subsection 2.20.2 SG1: Decide order of operations
The two operators in this expression are the
>
and or
(boolean logical OR). The or
operator has a very low precedence, much lower than any of the comparison operators. Therefore, the comparison will be evaluated first, followed by the logical or
.Subsection 2.20.3 SG2: Determine operator behavior based on operands
The
alpha
and beta
variables are integers, which are valid operands for the >
comparison. That expression evaluates to a boolean. That boolean and the integer variable gamma
will be used for operands for the or
operator. The or
operator allows basically any type of value to be used, with the result type dependent on which operand evaluates to True (from left to right). So the or
will evaluate either to a boolean (because of its left operand, the result of the >
operation) or an integer (because of its right operand gamma
).Subsection 2.20.4 SG3: Solve arithmetic, expression, or operation
-
In the first comparison,
alpha
is substituted for0
andbeta
is substituted for1
. Then, the>
determines if0
is greater than1
, which it is not. Therefore, the expression evaluates toFalse
.The boolean valueFalse
is used as the right operand. Each operand will be checked from left to right, with the result being the first operand that evaluates toTrue
according to the rules of Truthiness. SinceFalse
is nota value that evaluates to True in truthiness rules, the second operand is checked. The value5
is a Truthy value (any non-zero integer is considered True for the purposes of Truthiness), so5
is the value that is assigned toresult
.
Subsection 2.20.5 Questions to check understanding
-
Would putting parentheses around
beta or gamme
change the result?Answer.
Yes, but not in the way you might expect. The expressionbeta or gamme
will be evaluated first, and produce an integer (specifically1
since that is a Truthy value). Then, that result will be used as the right operand to the>
comparison, resulting in a boolean value (False
, since0 > 1
). -
What expression would actually ask the question, "is either beta or gamma greater than alpha?"
Answer.
You would need to repeat the comparison asalpha > beta or alpha > gamma
You have attempted of activities on this page.