Python Python 5 — Questions and Answers
Question 1: What does the `global` keyword do inside a Python function?
- Creates a new global variable
- Declares that a variable name refers to the module-level global variable (Correct answer)
- Prevents a variable from being modified
- Imports a variable from another module
Correct answer: Declares that a variable name refers to the module-level global variable
`global x` inside a function tells Python to use and potentially modify the `x` defined at the module level rather than creating a local one.
Question 2: Which built-in function applies a function to every item in an iterable and returns a map object?
- apply()
- filter()
- reduce()
- map() (Correct answer)
Correct answer: map()
`map(func, iterable)` applies `func` to each element and returns an iterator of the results.
Question 3: What is the output of `type(3.0)` in Python?
- <class 'int'>
- <class 'float'> (Correct answer)
- <class 'double'>
- <class 'number'>
Correct answer: <class 'float'>
`3.0` is a floating-point literal, so `type(3.0)` returns `<class 'float'>`.
Question 4: What does `'%s has %d items' % ('cart', 5)` produce?
- '%s has %d items'
- 'cart has 5 items' (Correct answer)
- TypeError
- 'cart has items'
Correct answer: 'cart has 5 items'
The `%` formatting operator substitutes `%s` with the string and `%d` with the integer from the tuple.
Question 5: Which Python data structure guarantees FIFO (first-in, first-out) ordering?
- list
- dict
- collections.deque used as a queue (Correct answer)
- set
Correct answer: collections.deque used as a queue
`collections.deque` with `append()` and `popleft()` provides O(1) FIFO queue operations.
Question 6: What is the purpose of `if __name__ == '__main__':` in a Python script?
- Define the main class
- Prevent the code block from running when the file is imported as a module
- Mark the entry point for the Python interpreter to start
- Both B and C (Correct answer)
Correct answer: Both B and C
This guard ensures the indented block runs only when the script is executed directly, not when imported, effectively marking the entry point.
Question 7: What does `sorted()` return compared to `list.sort()`?
- Both return a new sorted list
- `sorted()` returns a new list; `list.sort()` sorts in place and returns None (Correct answer)
- `list.sort()` returns a new list; `sorted()` sorts in place
- Both sort in place
Correct answer: `sorted()` returns a new list; `list.sort()` sorts in place and returns None
`sorted()` always returns a new sorted list, while `list.sort()` modifies the list in place and returns `None`.
What does the `global` keyword do inside a Python function?