Skip to main content

Section 1.10 Operation Precedence

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.10.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 = 2
beta = 1
delta = 3
omega = 2.5
theta = -1.3
kappa = 3.0

gamma = delta / (alpha + beta) % alpha

Subsection 1.10.2 SG1: Decide order of operations

The expression is the right-hand-side (RHS) of the statement: delta /(alpha + beta) % alpha. In this expression, the parentheses have the highest priority, so the addition inside of the parentheses will be evaluated first. Then, since division and modulo have the same priority, the division with delta will occur next, with the result module the final alpha

Subsection 1.10.3 SG2: Determine operator behavior based on operands

The expression alpha + beta is an addition between two integers, so will result in an integer. The subsequent division between delta (an integer) and that new integer will result in a float, since the float division operator is used. The final modulo will be between a float and an integer, which will produce a float.

Subsection 1.10.4 SG3: Solve arithmetic, expression, or operation

The variable alpha is substituted for the value 2 and the variable beta is substituted for the value 1. Adding them produces the integer 3.
The value of delta (3) is then used as the divisor, for the dividend of 1.0.
Then, the last alpha is substituted for 2, and 1.0 % 2 is calculated, with the final remainder of 1.0.
The value 1.0 is stored in gamma

Subsection 1.10.5 Questions to check understanding

  1. Is the left-hand-side (LHS) of the statement a variable? What type?
    Answer.
    Yes, the variable gamma will be a float.
  2. What is the resulting type after evaluating the right-hand-side (RHS)?
    Answer.
    A float.
  3. Would dividing using the // operator instead of the / operator change the type of the result?
    Answer.
    Yes, since the result of that division would be an integer (3), and all the other operations involved integers.
You have attempted of activities on this page.