Python Python 3 — Questions and Answers
Question 1: What is the purpose of the `__init__` method in a Python class?
- Destroy an object
- Initialize a new object's attributes (Correct answer)
- Define class-level variables
- Import class dependencies
Correct answer: Initialize a new object's attributes
`__init__` is the constructor that runs automatically when a new instance is created, setting initial attribute values.
Question 2: What does `dict.get('key', 'default')` return if 'key' is not in the dictionary?
- None
- KeyError
- 'default' (Correct answer)
- False
Correct answer: 'default'
`dict.get(key, default)` returns the default value instead of raising a KeyError when the key is missing.
Question 3: Which Python built-in function returns the length of an object?
- size()
- count()
- len() (Correct answer)
- length()
Correct answer: len()
`len()` returns the number of items in a sequence, collection, or other container object.
Question 4: What does a `try/except/finally` block guarantee about the `finally` clause?
- It runs only if no exception occurs
- It runs only if an exception occurs
- It always runs regardless of exceptions (Correct answer)
- It runs only after `except` handles an error
Correct answer: It always runs regardless of exceptions
The `finally` block always executes whether an exception was raised or not, making it ideal for cleanup.
Question 5: What is the result of `'hello'[::-1]` in Python?
- 'hello'
- 'olleh' (Correct answer)
- 'h'
- Error
Correct answer: 'olleh'
The slice `[::-1]` reverses the string by stepping backward through all characters.
Question 6: Which statement about Python's `set` type is correct?
- Sets preserve insertion order
- Sets allow duplicate elements
- Sets are unordered and contain unique elements (Correct answer)
- Sets are immutable
Correct answer: Sets are unordered and contain unique elements
Python sets are unordered collections that automatically enforce uniqueness — duplicates are silently ignored.
Question 7: What does the `zip()` function do in Python?
- Compress files
- Combine two or more iterables element-by-element into tuples (Correct answer)
- Merge two dictionaries
- Sort multiple lists simultaneously
Correct answer: Combine two or more iterables element-by-element into tuples
`zip()` pairs up elements from multiple iterables and returns an iterator of tuples.
What is the purpose of the `__init__` method in a Python class?