Functions are crucial in any programming language, enabling modularity and code reuse. They allow you to define a set of instructions that you can use repeatedly throughout your code. Let’s test your understanding of Python functions with these 12+ Multiple Choice Questions.
1. Which keyword is used to define a function in Python?
Answer:
Explanation:
In Python, the def keyword is used to declare or define a function.
2. What will be the output of the following code?
def greet():
print("Hello!")
print(greet())
Answer:
Explanation:
The function greet() prints “Hello!” but does not return any value. By default, Python functions return None if no return value is specified.
3. Which of the following is a correct function header?
Answer:
Explanation:
Functions in Python are defined using the def keyword, followed by the function name and parentheses.
4. What is the purpose of the return statement in functions?
Answer:
Explanation:
The return statement is used to exit a function and return a value.
5. Which of the following functions takes two arguments and returns their sum?
Answer:
Explanation:
The correct way to define a function that takes two arguments and returns their sum is option c.
6. How do you call a function named my_function?
Answer:
Explanation:
Functions are called by their name followed by parentheses.
7. Which of the following is the correct way to define a function that takes any number of positional arguments?
Answer:
Explanation:
The *args syntax in a function header allows the function to accept any number of positional arguments.
8. What is a lambda function in Python?
Answer:
Explanation:
A lambda function is a small, unnamed (anonymous) function defined using the lambda keyword.
9. Which of the following is a correct lambda function that squares a number?
Answer:
Explanation:
The correct syntax for a lambda function to square a number in Python is lambda x: x*x.
10. Which of the following functions is a recursive function?
Answer:
Explanation:
A recursive function is a function that calls itself in order to solve a problem.
11. What is the purpose of the global keyword in a function?
Answer:
Explanation:
The global keyword is used inside a function to refer to a variable that is defined in the global scope.
12. What is the output of the following code?
def add(x, y):
return x + y
def operate(func, x, y):
return func(x, y)
print(operate(add, 3, 4))
Answer:
Explanation:
The operate function takes another function as an argument and calls it with x and y. In this case, it calls the add function, which returns 3 + 4, i.e., 7.
13. Which of the following can be used as default values for function arguments?
Answer:
Explanation:
In Python, numbers, strings, lists, and many other types can be used as default values for function arguments.
I hope you found this MCQ series insightful! Testing your knowledge on functions can help solidify your understanding and make you more proficient in Python. Keep practicing and happy coding!