Exercise: Python

Questions for: Functions

How can you define a generator function that yields squares of numbers up to a given limit?
A:
def square_generator(limit):
    for i in range(limit):
        yield i**2
B:
generator square_generator(limit):
    for i in range(limit):
        return i**2
C:
def square_generator(limit):
    return (i**2 for i in range(limit))
D:
generator square_generator(limit):
    return [i**2 for i in range(limit)]
Answer: A
The correct definition for a generator function that yields squares of numbers up to a given limit is shown in option A.
How can you use the filter function to filter out even numbers from a list?
A:
filter(lambda x: x % 2 != 0, my_list)
B:
filter(lambda x: x % 2 == 0, my_list)
C:
filter(is_even, my_list)
D:
filter(is_odd, my_list)
Answer: A
The correct usage of the filter function to filter out even numbers is filter(lambda x: x % 2 != 0, my_list).
How can you define a lambda function that adds two numbers?
A:
lambda x, y: x + y
B:
def add(x, y): return x + y
C:
lambda add(x, y): x + y
D:
lambda add: x + y
Answer: A
The correct syntax for a lambda function that adds two numbers is lambda x, y: x + y.
What does the zip(*iterables) function do?
A:
It compresses files in a directory.
B:
It combines multiple iterables element-wise into tuples.
C:
It filters elements from an iterable based on a condition.
D:
It creates a zip archive of files.
Answer: B
The zip(*iterables) function in Python combines multiple iterables element-wise into tuples.
What is the purpose of the __enter__ and __exit__ methods in a Python class?
A:
To define the initialization and cleanup methods of a class.
B:
To define methods for adding and removing elements in a class.
C:
To create context managers for resource management.
D:
To define methods for comparison operations in a class.
Answer: C
The __enter__ and __exit__ methods in a Python class are used to create context managers for resource management, allowing proper setup and cleanup.
Ad Slot (Above Pagination)
Quiz