Free PCEP Operator Precedence and Binding Questions and Answers 1 — Questions and Answers
Question 1: What is the result of the following expression? `print(2 + 3 * 4)`
- 20
- 14 (Correct answer)
- 9
- A syntax error occurs
Correct answer: 14
In Python, the multiplication operator (`*`) has higher precedence than the addition operator (`+`). Therefore, `3 * 4` is evaluated first, resulting in 12. Then, `2 + 12` is evaluated, giving the final result of 14.
Question 2: What will be printed to the console after executing this code? `print(-4 ** 2)`
- 16
- 8
- -16 (Correct answer)
- -8
Correct answer: -16
The exponentiation operator (`**`) has a higher precedence than the unary minus operator (`-`). The expression is evaluated as `-(4 ** 2)`, which calculates to `-(16)`, resulting in -16.
Question 3: What is the output of the following expression? `print(10 // 3 % 2)`
- 0
- 1 (Correct answer)
- 1.5
- 3
Correct answer: 1
The floor division (`//`) and modulo (`%`) operators have the same precedence and are evaluated from left to right. First, `10 // 3` is calculated, which results in 3. Then, `3 % 2` is calculated, which results in 1.
Question 4: What is the result of this expression? `print(2 ** 3 ** 2)`
- 64
- 12
- 512 (Correct answer)
- 36
Correct answer: 512
The exponentiation operator (`**`) has right-to-left associativity. This means the expression is evaluated as `2 ** (3 ** 2)`. First, `3 ** 2` is calculated to be 9, and then `2 ** 9` is calculated, which is 512.
Question 5: What is the output of the following code? `print(5 * 2 > 8 and 3 + 4 == 7)`
- True (Correct answer)
- False
- 1
- An error occurs
Correct answer: True
First, the arithmetic and comparison expressions are evaluated. `5 * 2 > 8` becomes `10 > 8`, which is `True`. `3 + 4 == 7` becomes `7 == 7`, which is also `True`. Finally, the logical `and` operator evaluates `True and True`, resulting in `True`.
Question 6: What value is assigned to `result`? `result = (2 + 3) * 5 - 1`
- 16
- 20
- 24 (Correct answer)
- 14
Correct answer: 24
Expressions inside parentheses are always evaluated first. `(2 + 3)` results in 5. The expression then becomes `5 * 5 - 1`. Multiplication has higher precedence, so `5 * 5` is 25. Finally, `25 - 1` is 24.
Question 7: What is the output of this code? `print(not True or False)`
- True
- False (Correct answer)
- None
- SyntaxError
Correct answer: False
The `not` operator has higher precedence than the `or` operator. First, `not True` is evaluated to `False`. The expression then becomes `False or False`, which evaluates to `False`.
What is the result of the following expression?
`print(2 + 3 * 4)`