Functions in Python - Interview Questions and Answers
A function in Python is a block of code that performs a specific task. It can take arguments, process them, and return a value. Functions are defined using the def
keyword.
A function is defined using the def
keyword, followed by the function name and parameters (if any).
def my_function():
print("Hello, World!")
The return
statement is used to send a result from the function back to the caller. If no return
is specified, the function returns None
by default.
The different types of functions in Python include:
- Built-in functions (e.g.,
print()
,len()
) - User-defined functions (e.g., functions defined using
def
) - Lambda functions (anonymous functions)
- Recursive functions (functions that call themselves)
A lambda function is a small anonymous function defined using the lambda
keyword. It can take any number of arguments but can only have one expression.
square = lambda x: x ** 2
A regular function is defined using def
and can have multiple expressions, whereas a lambda function is defined using lambda
and can have only one expression. Lambda functions are often used for short, simple tasks.
Default arguments are values provided in a function definition that are used if no argument is passed for those parameters when the function is called.
def greet(name="User"):
print(f"Hello, {name}!")
Yes, the default argument values can be changed by passing new values when calling the function.
greet("Alice") # Hello, Alice!
Keyword arguments are arguments passed to a function by explicitly specifying the parameter name and its corresponding value.
def greet(name, age):
print(f"Name: {name}, Age: {age}")
greet(name="Alice", age=25)
- Positional arguments: Passed in the order defined in the function.
- Keyword arguments: Passed by explicitly specifying the parameter name and its value.
Variable-length arguments allow a function to accept any number of arguments. They are represented by *args
(for non-keyword arguments) and **kwargs
(for keyword arguments).
def func(*args, **kwargs):
print(args)
print(kwargs)
*args
allows a function to accept any number of positional arguments. It collects all extra positional arguments as a tuple.
def print_args(*args):
print(args)
**kwargs
allows a function to accept any number of keyword arguments. It collects all extra keyword arguments as a dictionary.
def print_kwargs(**kwargs):
print(kwargs)
Yes, a function can have both *args
and **kwargs
, but *args
must appear before **kwargs
.
def func(a, b, *args, **kwargs):
print(a, b)
print(args)
print(kwargs)
A recursive function is a function that calls itself to solve a problem. It typically has a base case to stop the recursion.
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
A base case is a condition in a recursive function that terminates the recursion. Without it, the recursion would continue indefinitely.
To prevent infinite recursion, always ensure that there is a base case that can be reached, and that the recursive call moves toward it.
- Local scope: Variables defined inside a function are local to that function.
- Global scope: Variables defined outside any function are global and can be accessed by any function.
The global
keyword allows a function to modify a global variable instead of creating a local one.
x = 5
def modify_global():
global x
x = 10
The nonlocal
keyword is used to modify variables in the nearest enclosing scope that is not global (i.e., the scope of the function in which the variable is declared).
def outer():
x = 10
def inner():
nonlocal x
x = 20
inner()
print(x) # 20
If a function returns None
, it means the function does not explicitly return any value. In Python, None
is the default return value for functions that do not have a return
statement.
The callable()
function checks if an object appears to be callable (i.e., if it can be called as a function). It returns True
if the object is callable, and False
otherwise.
callable(print) # True
callable(5) # False
is
: Checks if two objects are the same in memory (identity comparison).==
: Checks if the values of two objects are equal (value comparison).
Functions allow you to define a block of code once and reuse it multiple times, which reduces redundancy and improves code maintainability.
The return type is the data type of the value that a function returns, such as int
, str
, float
, or None
(if no value is returned).
Function annotations provide a way to attach metadata to function arguments and return values. These annotations are not enforced and are purely informational.
def add(a: int, b: int) -> int:
return a + b
Docstrings are used to document the function?s purpose, parameters, and return value. They are enclosed in triple quotes and can be accessed using the help()
function.
def add(a, b):
"""Adds two numbers."""
return a + b
Yes, functions can return other functions. This is often done in closures, where a function returns another function that remembers the scope of the original function.
def outer(x):
def inner(y):
return x + y
return inner
Together, *args
and **kwargs
allow a function to accept any number of positional and keyword arguments, respectively, making the function flexible in terms of the number of inputs.
def example(a, *args, b=2, **kwargs):
print(a, args, b, kwargs)
A higher-order function is a function that takes one or more functions as arguments, returns a function as a result, or both.
def add(x):
return lambda y: x + y
A closure is a function that remembers the environment in which it was created. It has access to variables from its enclosing scope even after that scope has finished execution.
def outer(x):
def inner(y):
return x + y
return inner
Exceptions in functions can be handled using a try
block followed by except
to catch and handle errors.
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
pass
: A placeholder that does nothing, used when a statement is required syntactically.return
: Exits a function and optionally returns a value.
You can call a function inside another function by simply invoking the function by its name.
def first():
print("First function")
def second():
first()
Yes, functions can be assigned to variables and called using those variables.
add = lambda x, y: x + y
print(add(2, 3)) # 5
A recursive function is a function that calls itself in order to solve a problem, often by breaking the problem into smaller subproblems.
Recursive functions can be optimized using memoization or converting them to iterative solutions to prevent deep recursion.
Functions can be passed as arguments by referring to them by their name.
def greet():
print("Hello!")
def execute(func):
func()
execute(greet) # Calling the function greet via execute
Functions help with code reusability, improve readability, enable modularity, and simplify debugging and testing.
No, Python requires that a function be defined before it is called.
Python does not support function overloading by default. However, you can simulate it using default arguments or variable-length arguments.
==
: Compares values of two objects.is
: Compares the identity of two objects (whether they are the same object).
The output will be 10
because function(5)
returns 5 * 2
.
A function signature consists of the function name, parameter list, and return type (if specified). It uniquely identifies a function.
The help()
function provides documentation on functions, classes, and modules. It displays information about the object passed to it.
Lists or arrays can be passed to functions as arguments, where they are received as variables.
def print_list(lst):
for item in lst:
print(item)
The map()
function applies a given function to all items in an iterable (list, tuple, etc.) and returns an iterator.
result = map(lambda x: x * 2, [1, 2, 3])
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
Yes, a function can return multiple values, often in the form of a tuple.
def calculate(a, b):
return a + b, a - b
The def
keyword is used to define a function in Python, followed by the function name and parameters.
Tutorials
Random Blogs
- What Is SEO and Why Is It Important?
- What is YII? and How to Install it?
- Where to Find Free Datasets for Your Next Machine Learning & Data Science Project
- Top 10 Blogs of Digital Marketing you Must Follow
- Mastering Python in 2025: A Complete Roadmap for Beginners
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- 5 Ways Use Jupyter Notebook Online Free of Cost
- Google’s Core Update in May 2020: What You Need to Know
- AI in Cybersecurity: The Future of Digital Protection
- The Ultimate Guide to Data Science: Everything You Need to Know