Python Multiple Choice Questions on “Precedence and Associativity – 1”.
1. The value of the expressions 4/(3*(2-1)) and 4/3*(2-1) is the same.
a) True
b) False
Answer: a
Clarification: Although the presence of parenthesis does affect the order of precedence, in the case shown above, it is not making a difference. The result of both of these expressions is 1.333333333. Hence the statement is true.
2. What will be the value of the following Python expression?
a) 4
b) 7
c) 2
d) 0
Answer: b
Clarification: The order of precedence is: %, +. Hence the expression above, on simplification results in 4 + 3 = 7. Hence the result is 7.
3. Evaluate the expression given below if A = 16 and B = 15.
a) 0.0
b) 0
c) 1.0
d) 1
Answer: b
Clarification: The above expression is evaluated as: 16%15//16, which is equal to 1//16, which results in 0.
4. Which of the following operators has its associativity from right to left?
a) +
b) //
c) %
d) **
Answer: d
Clarification: All of the operators shown above have associativity from left to right, except exponentiation operator (**) which has its associativity from right to left.
5. What will be the value of x in the following Python expression?
a) 43
b) 44
c) 22
d) 23
Answer: b
Clarification: The expression shown above is an example of explicit conversion. It is evaluated as int(43.55+1) = int(44.55) = 44. Hence the result of this expression is 44.
6. What is the value of the following expression?
a) (6.0, 16.0)
b) (6.00, 16.00)
c) (6, 16)
d) (6.00, 16.0)
Answer: a
Clarification: The result of the expression shown above is (6.0, 16.0). This is because the result is automatically rounded off to one decimal place.
7. Which of the following is the truncation division operator?
a) /
b) %
c) //
d) |
Answer: c
Clarification: // is the operator for truncation division. It is called so because it returns only the integer part of the quotient, truncating the decimal part. For example: 20//3 = 6.
8. What are the values of the following Python expressions?
2**(3**2) (2**3)**2 2**3**2
a) 64, 512, 64
b) 64, 64, 64
c) 512, 512, 512
d) 512, 64, 512
Answer: d
Clarification: Expression 1 is evaluated as: 2**9, which is equal to 512. Expression 2 is evaluated as 8**2, which is equal to 64. The last expression is evaluated as 2**(3**2). This is because the associativity of ** operator is from right to left. Hence the result of the third expression is 512.
9. What is the value of the following expression?
a) (1.0, 4.0)
b) (1.0, 1.0)
c) (4.0. 1.0)
d) (4.0, 4.0)
Answer: a
Clarification: The above expressions are evaluated as: 2/2, 8/2, which is equal to (1.0, 4.0).
10. What is the value of the following expression?
a) 8
b) 8.0
c) 8.3
d) 8.33
Answer: b
Clarification: The expression shown above is evaluated as: float( 7+1) = float(8) = 8.0. Hence the result of this expression is 8.0.