Section 2.16 Assign Booleans
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.16.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 = 42
beta = 1
gamma = 5
result = beta <= alpha
Subsection 2.16.2 SG1: Decide order of operations
There is only a single operator, the
<=
(less than or equal to operator), so that is the only one that needs to be evaluated.Subsection 2.16.3 SG2: Determine operator behavior based on operands
The
<=
operator will determine if one value is less than or equal than the other, and requires that they be compatible types. Integers and floats are compatible with each other, but in this case both alpha
and beta
are integers, which are definitely compatible. The result will be a boolean value.Subsection 2.16.4 SG3: Solve arithmetic, expression, or operation
First,
beta
is substituted for 1
and alpha
is substituted for 42
. Then, the <=
determines if 1
is less than or equal to 42
, which it is. Therefore, the expression evaluates to True
, which is assigned to the variable result
.Subsection 2.16.5 Questions to check understanding
-
If the
>
operator was used, would theresult
still be a boolean variable?Answer.
Yes, any comparison operator used on two integers will produce a boolean (although that value could be eitherTrue
orFalse
). -
If
alpha
was a float, would theresult
still be a boolean variable?Answer.
Yes, the comparison operators allow you to combine integers and floats, and the result will still be a boolean value.
You have attempted of activities on this page.