Python Core Syntax 3 — Questions and Answers
Question 1: What will `x = [1, 2, 3]; print(x[-1])` output?
- 1
- 2
- 3 (Correct answer)
- IndexError
Correct answer: 3
Negative indexing in Python counts from the end; `-1` refers to the last element, which is `3`.
Question 2: Which of the following correctly unpacks a tuple `t = (10, 20, 30)` into three variables?
- a, b, c = t (Correct answer)
- a = b = c = t
- (a), (b), (c) = t
- a; b; c = t
Correct answer: a, b, c = t
Tuple unpacking with `a, b, c = t` assigns each element to a corresponding variable in order.
Question 3: What is the purpose of the `pass` statement in Python?
- Skips the current loop iteration
- Exits a function immediately
- Acts as a placeholder where syntax requires a statement (Correct answer)
- Passes a value to the caller
Correct answer: Acts as a placeholder where syntax requires a statement
`pass` is a null operation used as a syntactic placeholder when a block is required but no action is needed.
Question 4: What does `print(10 % 3)` output?
- 3
- 1 (Correct answer)
- 0
- 3.33
Correct answer: 1
The `%` modulus operator returns the remainder of divison; `10 % 3` is `1` because `10 = 3*3 + 1`.
Question 5: Which of the following is the correct way to write a single-line conditional expression (ternary) in Python?
- x = 1 if cond ? 2
- x = cond ? 1 : 2
- x = 1 if cond else 2 (Correct answer)
- x = (cond) then 1 else 2
Correct answer: x = 1 if cond else 2
Python's ternary expression uses the syntax `value_if_true if condition else value_if_false`.
Question 6: What is the output of `print(2 ** 3 ** 2)`?
- 64
- 512 (Correct answer)
- 8
- 36
Correct answer: 512
The `**` exponentiation operator is right-associative, so `2 ** 3 ** 2` = `2 ** 9` = `512`.
Question 7: Which built-in function returns the number of items in a sequence?
- size()
- count()
- len() (Correct answer)
- length()
Correct answer: len()
`len()` is the built-in function that returns the number of items in a sequence or collection.
What will `x = [1, 2, 3]; print(x[-1])` output?