Exercise: Python

Questions for: Functions

What will be the output of the following code snippet?
def add(a, b):
    return a + b

numbers = [1, 2, 3, 4]
result = add(*numbers)
print(result)
A:
10
B:
1234
C:
[1, 2, 3, 4]
D:
Error
Answer: A
The *numbers syntax unpacks the list, and the function add adds all elements together.
What does the term "function overloading" mean?
A:
Defining multiple functions with the same name but different parameters
B:
A function calling itself
C:
The process of reducing the size of a function
D:
Using multiple functions to overload the program
Answer: A
Function overloading in Python involves defining multiple functions with the same name but different parameters.
What will be the output of the following code snippet?
def power(x, n=2):
    return x ** n

result = power(2, 3)
print(result)
A:
8
B:
6
C:
64
D:
2
Answer: A
The function power raises 2 to the power of 3, resulting in 8.
What is the purpose of the locals() function?
A:
Retrieves a list of local variables
B:
Converts a string to lowercase
C:
Checks if a variable is of a certain type
D:
Retrieves a dictionary of local symbols
Answer: D
The locals() function returns a dictionary representing the current local symbol table.
What is the purpose of the sorted() function?
A:
Sorts elements of a list in ascending order
B:
Reverses the order of elements in a list
C:
Shuffles elements randomly in a list
D:
Checks if a variable is of a certain type
Answer: A
The sorted() function is used to sort the elements of an iterable, such as a list, in ascending order.
Ad Slot (Above Pagination)
Quiz