Python Operators and Expressions 2 — Questions and Answers
Question 1: What does the walrus operator `:=` do in Python?
- Assigns a value and returns it in the same expression (Correct answer)
- Compares two values for equality
- Performs integer division
- Creates a new variable in a separate scope
Correct answer: Assigns a value and returns it in the same expression
The walrus operator `:=` (assignment expression) assigns a value to a variable and simultaneously returns that value within an expression.
Question 2: What is the result of `0.1 + 0.2 == 0.3` in Python?
- True
- False (Correct answer)
- None
- Raises a TypeError
Correct answer: False
Due to floating-point representation errors, `0.1 + 0.2` evaluates to `0.30000000000000004`, which is not equal to `0.3`.
Question 3: What does `x **= 2` do when `x = 3`?
- Sets x to 9 (Correct answer)
- Sets x to 6
- Sets x to 8
- Sets x to 1
Correct answer: Sets x to 9
`**=` is the in-place exponentiation operator, so `x **= 2` is equivalent to `x = x ** 2`, giving `3 ** 2 = 9`.
Question 4: What is the value of `bool(0) or bool(1)`?
- True (Correct answer)
- False
- 0
- 1
Correct answer: True
`bool(0)` is `False` and `bool(1)` is `True`; `False or True` evaluates to `True`.
Question 5: What does the expression `'abc' * 3` evaluate to?
- 'abcabcabc' (Correct answer)
- 'abc3'
- 9
- Raises a TypeError
Correct answer: 'abcabcabc'
The `*` operator with a string and integer repeats the string that many times, producing `'abcabcabc'`.
Question 6: Which operator checks identity (same object in memory) in Python?
- is (Correct answer)
- ==
- ===
- eq
Correct answer: is
The `is` operator checks whether two variables point to the exact same object in memory, unlike `==` which checks value equality.
Question 7: What is the result of `not not True`?
- True (Correct answer)
- False
- None
- Raises a SyntaxError
Correct answer: True
`not True` is `False`, and `not False` is `True`, so double negation returns the original value.
What does the walrus operator `:=` do in Python?