Python Data Types and Variables 5 — Questions and Answers
Question 1: What is the result of `type(lambda: None)`?
- <class 'NoneType'>
- <class 'function'> (Correct answer)
- <class 'lambda'>
- <class 'method'>
Correct answer: <class 'function'>
Lambda expressions create anonymous functions; their type is `function`.
Question 2: How do you check if variable `x` is of type `str` using the recommended approach?
- type(x) == str
- x.type() is str
- isinstance(x, str) (Correct answer)
- x.__class__ == 'str'
Correct answer: isinstance(x, str)
`isinstance(x, str)` is preferred because it also handles subclasses of `str`.
Question 3: What does Python's dynamic typing mean?
- Variables are typed at compile time
- Variable types are determined and can change at runtime (Correct answer)
- All variables must be declared before use
- Variables cannot change type once assigned
Correct answer: Variable types are determined and can change at runtime
In Python, type is associated with the object, not the variable, and the same name can point to objects of different types at runtime.
Question 4: What is the value of `int(3.9)`?
- 4
- 3 (Correct answer)
- 3.9
- ValueError
Correct answer: 3
`int()` truncates toward zero, so `int(3.9)` is `3`, not 4.
Question 5: Which Python keyword is used to annotate a variable's type without assigning it?
- declare
- var
- : (Correct answer)
- type
Correct answer: :
PEP 526 syntax `x: int` annotates the variable type using a colon without assignment.
Question 6: What is the output of `str(True)`?
- '1'
- 'true'
- 'True' (Correct answer)
- 'bool'
Correct answer: 'True'
`str(True)` returns the string `'True'` with a capital T.
Question 7: Which of the following correctly unpacks values into multiple variables?
- a, b = (1, 2) (Correct answer)
- a = b = (1, 2)
- [a, b] = 1, 2 -> only works in Python 2
- unpack(1, 2) -> a, b
Correct answer: a, b = (1, 2)
Tuple unpacking `a, b = (1, 2)` assigns 1 to `a` and 2 to `b` simultaneously.
What is the result of `type(lambda: None)`?