WorksheetsFunctions and Modules
Total questions: 10
Worksheet time: 5mins
State the purpose of using args and *kwargs in Python functions?
To specify required arguments
To handle a variable number of arguments
To define default arguments
To restrict the number of arguments passed to a function
In Python, what is the role of a lambda function?
To define a function that can be called with any number of arguments
To create a function without a name
To handle exceptions in a program
To import external modules into a Python script
Which keyword is used to define a default argument in a Python function?
default
def
var
none
What will be the output of the following
from import factorial
print(math.factorial(5))
25
10
120
error bcz factorial is not a module in math
Suppose a function called add() is defined in a module called adder.py. Which of the following code snippets correctly show how to import and use the add() function? Select all that apply.
import add from adder
result = add(2, 3)
from adder import add
result = add(2, 3)
from adder import add
result = adder.add(2, 3)
import add
result = adder.add(2, 3)
How can you use a lambda function to sort a list of tuples based on the second element?
my_list = [(1, 3), (3, 2), (2, 1)]
sorted(my_list, key=lambda x: x[0])
sorted(my_list, key=lambda x: x[1])
sorted(my_list, key=lambda x: x[2])
sorted(my_list, key=lambda x: x)
Predict the output of the following code
def func(a, b=[]):
b.append(a)
return b
result1 = func(1)
result2 = func(2, [])
result3 = func(3)
print(result1)
print(result2)
print(result3)
[1] [2] [3]
[1, 3] [2] [3]
[1, 3] [2] [1, 3]
[1] [2] [1, 3]
Predict the output of the following code
def add_items(item, items=None):
if items is None:
items = []
items.append(item)
return items
list1 = add_items('apple')
list2 = add_items('banana', [])
list3 = add_items('orange')
print(list1)
print(list2)
print(list3)
['apple', 'orange'] ['banana'] ['apple', 'orange']
['apple', 'orange'] ['banana'] ['orange']
['apple'] ['banana'] ['apple', 'orange']
['apple'] ['banana'] ['orange']
What will be the output of the following code?
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(2)
g = make_incrementor(6)
print(f(42), g(42))
44 48
44 42
42 48
Error
