Python Operators and Expressions 4 — Questions and Answers
Question 1: What does the expression `lambda x: x * 2` create?
- An anonymous function that doubles its argument (Correct answer)
- A generator that yields doubled values
- A class method
- A list comprehension
Correct answer: An anonymous function that doubles its argument
`lambda x: x * 2` creates an anonymous (lambda) function that takes one argument and returns it multiplied by 2.
Question 2: What is the result of `True + True + False` in Python?
- 2 (Correct answer)
- True
- 1
- Raises a TypeError
Correct answer: 2
In Python, `True` equals `1` and `False` equals `0` in arithmetic contexts, so `1 + 1 + 0 = 2`.
Question 3: Which expression correctly checks if a variable `n` is between 1 and 10 (inclusive)?
- 1 <= n <= 10 (Correct answer)
- n >= 1 and <= 10
- n between 1 and 10
- 1 =< n =< 10
Correct answer: 1 <= n <= 10
Python supports chained comparisons, so `1 <= n <= 10` is the correct and idiomatic way to check a range.
Question 4: What is the value of `~5` in Python?
- -6 (Correct answer)
- 6
- -5
- 4
Correct answer: -6
The bitwise NOT operator `~` inverts all bits; for integer `n`, `~n` equals `-(n + 1)`, so `~5 = -6`.
Question 5: What does `a, b = b, a` demonstrate in Python?
- Tuple unpacking for variable swapping (Correct answer)
- Multiple assignment with type conversion
- Parallel assignment with copying
- A syntax error in disguise
Correct answer: Tuple unpacking for variable swapping
Python evaluates the right side as a tuple `(b, a)` first, then unpacks it into `a` and `b`, effectively swapping them.
Question 6: What is the result of `2 ** 3 ** 2` in Python?
- 512 (Correct answer)
- 64
- 8
- Raises a SyntaxError
Correct answer: 512
The `**` operator is right-associative, so `2 ** 3 ** 2` is evaluated as `2 ** (3 ** 2) = 2 ** 9 = 512`.
Question 7: What does `5 | 3` evaluate to in Python?
- 7 (Correct answer)
- 1
- 15
- 5
Correct answer: 7
`5` is `101` and `3` is `011` in binary; bitwise OR gives `111`, which is `7`.
What does the expression `lambda x: x * 2` create?