Skip to main content

Section 1.20 Boolean Truthiness

Subgoals for evaluating an assignment statement.

  1. Decide order of operations
    1. Decompose as necessary
  2. Determine operator behavior based on operands
    1. Operator and operands must be compatible
  3. Solve arithmetic, expression, or operation
    1. Decompose as necessary

Subsection 1.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 1.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 1.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 1.20.4 SG3: Solve arithmetic, expression, or operation

  1. In the first comparison, alpha is substituted for 0 and beta is substituted for 1. Then, the > determines if 0 is greater than 1, which it is not. Therefore, the expression evaluates to False.
    The boolean value False is used as the right operand. Each operand will be checked from left to right, with the result being the first operand that evaluates to True according to the rules of Truthiness. Since False is nota value that evaluates to True in truthiness rules, the second operand is checked. The value 5 is a Truthy value (any non-zero integer is considered True for the purposes of Truthiness), so 5 is the value that is assigned to result.

Subsection 1.20.5 Questions to check understanding

  1. Would putting parentheses around beta or gamme change the result?
    Answer.
    Yes, but not in the way you might expect. The expression beta or gamme will be evaluated first, and produce an integer (specifically 1 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, since 0 > 1).
  2. What expression would actually ask the question, "is either beta or gamma greater than alpha?"
    Answer.
    You would need to repeat the comparison as alpha > beta or alpha > gamma
You have attempted of activities on this page.