Section 2.20 Boolean Truthiness
Subgoals for evaluating an assignment statement.
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,
alphais substituted for0andbetais substituted for1. Then, the>determines if0is greater than1, which it is not. Therefore, the expression evaluates toFalse.The boolean valueFalseis used as the right operand. Each operand will be checked from left to right, with the result being the first operand that evaluates toTrueaccording to the rules of Truthiness. SinceFalseis nota value that evaluates to True in truthiness rules, the second operand is checked. The value5is a Truthy value (any non-zero integer is considered True for the purposes of Truthiness), so5is the value that is assigned toresult.
Subsection 2.20.5 Questions to check understanding
-
Would putting parentheses around
beta or gammachange the result?Answer.
-
What expression would actually ask the question, "is either beta or gamma greater than alpha?"
You have attempted of activities on this page.
