PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python » Interview Questions » Top 20+ Python Functions and Modules Interview Questions with Answers

Top 20+ Python Functions and Modules Interview Questions with Answers

Updated on: April 16, 2025 | Leave a Comment

Understanding of functions and modules is fundamental to writing efficient and maintainable code. In technical interviews, these concepts are frequently tested to gauge a candidate’s proficiency in core Python principles.

This article aims to equip you with a comprehensive set of 20+ interview questions and answers, covering essential aspects of Python functions and modules. Whether you’re a seasoned programmer looking to brush up or a newcomer preparing for your first interview, this guide will provide valuable insights and practical examples to solidify your knowledge and boost your confidence.

Also Read:

  • Python Interview Questions and Answers: A guide to prepare for Python Interviews
  • Python functions: Complete Guide to understand functions in Python
  • Python functions Exercise
  • Python functions Quiz

1. What are functions in Python? Explain their purpose

Level: Beginner

A function in Python is a block of reusable code designed to perform a specific task.

Functions in Python are defined using the def keyword, followed by the function name, parentheses (which may include parameters), and a colon. The function body is indented.

Functions help:

  • Improve code readability and reusability.
  • Break down complex problems into smaller, manageable parts.
  • Avoid redundancy by using reusable code.

Example

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))  # Output: Hello, Alice!Code language: Python (python)

2. What are the types of functions in Python?

Level: Beginner

Functions in Python can be categorized into:

  1. Built-in Functions: Predefined functions like len(), print(), max().
  2. User-defined Functions: Functions created by the user.
  3. Lambda Functions: Anonymous, single-expression functions.

3. What are *args and kwargs in Python functions?

Level: Intermediate

The *args and kwargs you to write flexible and reusable functions that can accept an arbitrary number of arguments. You can use both in a function, but *args must come before **kwargs in the function definition.

*args

  • *args allows a function to accept any number of positional arguments.
  • Inside the function, args is treated as a tuple containing all the additional positional arguments passed to the function.

**kwargs

  • **kwargs allows a function to accept any number of keyword arguments.
  • Inside the function, kwargs is treated as a dictionary where the keys are the argument names and the values are the corresponding values passed to the function.

Example:

def example_function(*args, **kwargs):
    print("Args:", args)
    print("Kwargs:", kwargs)

example_function(1, 2, 3, name="Alice", age=25)
# Output:
# Args: (1, 2, 3)
# Kwargs: {'name': 'Alice', 'age': 25}Code language: Python (python)

Practical Use Cases

  • Functions that need to handle a flexible number of arguments.
  • Wrapper functions or decorators where the exact arguments are not known in advance.

By using *args and **kwargs, you can write more general, reusable, and adaptable code.

4. What is the difference between return and print in a function?

Level: Beginner

return

  • The return statement is used to pass a value from a function to the caller. It effectively “exits” the function and sends data back to the point where the function was called.
  • The value returned by return can be assigned to a variable, used in further calculations, or passed to other functions.
  • You can return multiple values as a tuple.
  • Without a return statement, a function implicitly returns None.

print()

  • print is used to display output (text or values) on the console. It’s meant for debugging or user interaction, not for passing data between parts of a program.
  • print is purely for displaying information. It does not affect the flow of data in a program

5. What are Python modules, and why are they used?

Level: Beginner

Modules are Python files containing reusable code like functions, classes, or variables. They allow code to be organized and reused across different programs.

Benefits:

  • Code reusability
  • Better organization
  • Avoid duplication

6. How do you import modules in Python? Explain the various ways

Level: Beginner

Modules can be imported using the import keyword. Common methods are:

Import the entire module:

import math
print(math.sqrt(16))  # Output: 4.0Code language: Python (python)

Import specific functions or variables:

from math import sqrt
print(sqrt(16))  # Output: 4.0Code language: Python (python)

Use aliases:

import math as m
print(m.sqrt(16))  # Output: 4.0Code language: Python (python)

7. What is the difference between a module and a package in Python?

Level: Intermediate

In Python, both modules and packages are used to organize and reuse code, but they serve slightly different purposes. Here’s the difference between the two:

Module

  • Definition: A module is a single Python file that contains Python code, such as functions, classes, and variables. The file has a .py extension.
  • Purpose: Modules are used to logically organize code into smaller, reusable components.
  • How to Use: To use a module, you import it into your script using the import statement.

Package

  • Definition: A package is a collection of modules organized in a directory. It contains an __init__.py file (though optional in Python 3.3 and later) to indicate that the directory is a package.
  • Purpose: Packages are used to structure large projects by organizing related modules into a directory hierarchy.
  • How to Use: You can import modules from a package using dot notation.

Key Points:

  • A module is just a .py file.
  • It can contain variables, functions, classes, and runnable code.
  • Built-in modules like math and os are examples of standard Python modules.
  • A package is a directory that contains multiple related modules.
  • The __init__.py file can be empty or contain initialization code for the package.
  • Packages support hierarchical structuring of modules.

Suppose you have a package named my_package with the following structure:

my_package/
    __init__.py
    math_utils.py
    string_utils.pyCode language: Python (python)

math_utils.py:

def add(a, b):
    return a + bCode language: Python (python)

string_utils.py:

def capitalize_words(text):
    return " ".join(word.capitalize() for word in text.split())Code language: Python (python)

You can use the package in another script:

from my_package import math_utils, string_utils
print(math_utils.add(5, 3)) # Output: 8
print(string_utils.capitalize_words("hello world")) # Output: "Hello World"Code language: Python (python)

Key Differences

FeatureModulePackage
DefinitionA single Python file (.py).A directory containing multiple modules.
OrganizationUsed to organize smaller chunks of code.Used to organize multiple modules into a hierarchy.
File StructureA .py file.A directory with an __init__.py file and other modules.
UsageImport the .py file directly.Import using dot notation (package.module).

8. What is the purpose of the __name__ == "__main__" construct?

Level: Intermediate

The if __name__ == "__main__": construct in Python is used to differentiate between when a script is run directly and when it is imported as a module in another script.

  • When a Python script is executed, the special variable __name__ is set to "__main__".
  • If the script is imported as a module, __name__ is set to the name of the module (i.e., the file name without the .py extension).

This construct ensures that certain code is executed only when the script is run directly, not when it is imported.

Example

File: example.py

def greet():
    print("Hello, World!")

if __name__ == "__main__":
    print("This script is being run directly.")
    greet()Code language: Python (python)

When run directly:

$ python example.py
This script is being run directly.
Hello, World!Code language: Python (python)

When imported as a module:

import example

# Output:
# (Nothing is printed because the code inside the `if __name__ == "__main__":` block is skipped.)Code language: Python (python)

Purpose

  • Prevents unintended execution of code when the script is imported as a module.
  • Useful for testing and modular programming by keeping reusable functions or classes separate from executable code.

9. What are decorators in Python? How are they used?

Level: Intermediate

Decorators in Python are special functions that modify or enhance the behavior of other functions or methods without changing their actual code. They are a powerful and concise way to add functionality to existing functions or methods.

Decorators wrap a function, taking it as an argument, and returning a new function that adds some additional behavior.

Use Cases:

  1. Logging: Automatically log function calls or outputs.
  2. Access Control: Enforce permissions or user roles.
  3. Caching: Store results of expensive function calls.
  4. Timing: Measure execution time of functions.

Decorators are a key feature of Python for creating reusable, modular, and cleaner code.

Example:

In Example 1, the my_decorator function wraps another function (e.g., say_hello) with additional behavior, such as printing messages before and after the wrapped function runs.

Using the @my_decorator syntax, the say_hello function gets enhanced without modifying its original definition.

def my_decorator(func):
    def wrapper():
        print("Something before the function runs.")
        func()
        print("Something after the function runs.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()Code language: Python (python)

Output:

Something before the function runs.
Hello!
Something after the function runs.

10. What are Python’s built-in modules? Name a few commonly used ones

Level: Beginner

Python includes several built-in modules, such as:

  • os: Interact with the operating system.
  • sys: Access system-specific parameters and functions.
  • math: Perform mathematical operations.
  • random: Generate random numbers.
  • datetime: Work with dates and times.

11. Can functions return multiple values? If yes, then how?

Level: Intermediate

Yes, functions in Python can return multiple values by using tuples, lists, dictionaries, or other data structures.

A function can return multiple values by separating them with commas. These values are implicitly packed into a tuple, which can then be unpacked when the function is called.

Example:

def calculate(a, b):
    return a + b, a - b, a * b

# Calling the function
result = calculate(10, 5)
print(result)  # Output: (15, 5, 50)

# Unpacking the result
add, sub, mul = calculate(10, 5)
print(add)  # Output: 15
print(sub)  # Output: 5
print(mul)  # Output: 50Code language: Python (python)

Why is it used?

  1. To return related values together: For example, returning a calculation result and its metadata (e.g., value and status).
  2. Improves readability and organization: Instead of creating multiple separate functions for different outputs, you can combine related outputs into one function.
  3. Avoids global variables: Functions can return multiple values instead of modifying global variables.

12. What is a default, positional, and keyword argument in a function?

Level: Intermediate

1. Default Arguments

Default arguments allow you to specify a default value for a parameter in the function definition. If no value is provided during the function call, the default value is used.

Example:

def greet(name, message="Hello"):
    print(f"{message}, {name}!")

greet("Alice")          # Output: Hello, Alice!
greet("Bob", "Hi")      # Output: Hi, Bob!Code language: Python (python)

2. Positional Arguments

Positional arguments are assigned based on their position in the function call. The order in which the arguments are provided must match the function’s parameter order.

Example:

def add(a, b):
    return a + b

print(add(2, 3))  # Output: 5Code language: Python (python)

3. Keyword Arguments

Keyword arguments are explicitly passed to the function using parameter names as keys. This allows you to specify arguments in any order and makes the code more readable.

Example:

def introduce(name, age):
    print(f"My name is {name} and I am {age} years old.")

introduce(age=25, name="Alice")  # Output: My name is Alice and I am 25 years old.Code language: Python (python)

Key Differences

  • Default Arguments: Provide fallback values for parameters.
  • Positional Arguments: Rely on the order of arguments in the function call.
  • Keyword Arguments: Use parameter names to explicitly specify argument value

Combined Example

Here’s how you can mix these argument types in a single function:

def profile(name, age, country="USA"):
    print(f"Name: {name}, Age: {age}, Country: {country}")

# Using positional and keyword arguments
profile("Bob", age=30, country="Canada")  
# Output: Name: Bob, Age: 30, Country: CanadaCode language: Python (python)

13. What is a recursive function and how do you create it?

Level: Intermediate

A recursive function in Python is a function that calls itself during its execution. This allows the function to solve problems by breaking them into smaller sub-problems of the same type.

Steps to create a recursive function:

  1. Define the function.
  2. Include a base case to tops the recursion to prevent an infinite loop.
  3. Add a recursive case where the function calls itself with modified parameters to break the problem into smaller parts.

Example: Factorial calculation

def factorial(n):
    # Base case
    if n == 0 or n == 1:
        return 1
    # Recursive case
    return n * factorial(n - 1)

# Test the recursive function
print(factorial(5))  # Output: 120Code language: Python (python)

Explanation:

  • Base Case: If n is 0 or 1, return 1.
  • Recursive Case: Multiply n by the factorial of n-1.

When to Use Recursion:

  • When a problem can be divided into smaller, similar sub-problems (e.g., mathematical computations, tree traversals, etc.).
  • When the recursive solution is simpler and more readable than an iterative solution.
  • Performance Consideration: Recursive functions can be memory-intensive due to the call stack. In such cases, iterative solutions might be more efficient.

14. Can we assign a new name to a function and call it through the new name? If yes, then how?

Level: Intermediate

Yes, in Python, you can assign a new name to an existing function and call it using the new name. Functions in Python are treated as first-class objects, meaning they can be assigned to variables, passed as arguments, or returned from other functions.

When you assign a new name to a function, it doesn’t create a copy of the function. The new name is just another reference to the same function object.

Example:

def greet(name):
    print(f"Hello, {name}!")

# Assign a new name to the function
welcome = greet

# Call the function using the new name
welcome("Alice")  # Output: Hello, Alice!

# Original function name still works
greet("Bob")  # Output: Hello, Bob!Code language: Python (python)

Use Cases:

  • Alias for Readability: Create shorter or more context-specific names for functions.
  • Dynamic Assignment: Assign functions to variables based on conditions (e.g., creating a simple function dispatcher).

15. How to create an inner function?

Level: Intermediate

An inner function is a function defined inside another function. It is also known as a nested function. Inner functions are typically used when a function is only relevant to the enclosing (outer) function or needs access to its variables.

Example:

def outer_function(name):
    def inner_function():
        print(f"Hello, {name}!")  # Accessing outer function's variable
    
    # Call the inner function
    inner_function()

# Call the outer function
outer_function("Alice")  # Output: Hello, Alice!Code language: Python (python)

Explanation:

  • inner_function is defined inside outer_function.
  • It can access the variable name from the enclosing function due to Python’s closures.

Why Use Inner Functions?

  1. Encapsulation: Inner functions are hidden from the outside and can only be accessed within the outer function, keeping the code modular.
  2. Reusability within a Scope: If some logic needs to be reused within the outer function, an inner function can help avoid code duplication.
  3. Closures: Inner functions can access variables from their enclosing scope, making them useful for maintaining state or context.

16. What are docstrings in a function?

Level: Beginner

Docstrings are multi-line strings used to document a function, class, or module. They are defined using triple quotes.

Example:

def example():
    """This is a docstring example."""
    return "Hello"

print(example.__doc__)  # Output: This is a docstring example.Code language: Python (python)

17. Explain lambda functions

Level: Intermediate

A lambda function in Python is a small, anonymous function defined using the lambda keyword. It is typically used for short, simple operations and is limited to a single expression.

When you need a quick, disposable function that doesn’t need to be reused, a lambda function is a great fit.

Syntax: lambda arguments: expression

  • arguments: Input parameters to the function.
  • expression: A single computation or return value.

Here’s an example of a lambda function that adds two numbers:

# Lambda function
add = lambda a, b: a + b
print(add(3, 5))  # Output: 8Code language: Python (python)

Use Cases:

Using Lambdas in map(), filter(), and reduce():

numbers = [1, 2, 3, 4, 5]

# Double each number using map()
doubled = map(lambda x: x * 2, numbers)
print(list(doubled))  # Output: [2, 4, 6, 8, 10]

# Filter even numbers
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))  # Output: [2, 4]Code language: Python (python)

Sorting with Custom Keys:

words = ["apple", "banana", "cherry"]
sorted_words = sorted(words, key=lambda x: len(x))
print(sorted_words)  # Output: ['apple', 'banana', 'cherry']Code language: Python (python)

Conclude with a practical statement:

“I would use lambda functions when I need a simple, one-liner function for functional programming operations like map, filter, or sorted. However, for more complex logic or reusable functions, I would prefer using def to maintain readability and clarity.”

This shows that you not only understand lambda functions but also know when and when not to use them!

18. Explain filter(), map(), and reduce() functions

Level: Intermediate

1. filter()

The filter() function is used to filter elements from an iterable (like a list) based on a condition (a function that returns True or False).

It is useful in removing invalid data, filtering items based on conditions, etc.

Example:

numbers = [1, 2, 3, 4, 5, 6]

# Filter even numbers
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens))  # Output: [2, 4, 6]Code language: Python (python)

In this example, the lambda function checks if a number is even, and filter() returns only those elements that satisfy this condition.

2. map()

The map() function applies a given function to each element of an iterable and returns a new iterable with the transformed elements.

It is commonly used for transforming data (e.g., converting units, applying calculations).

Example:

numbers = [1, 2, 3, 4, 5]

# Double each number
doubled = map(lambda x: x * 2, numbers)
print(list(doubled))  # Output: [2, 4, 6, 8, 10]Code language: Python (python)

In this example, the lambda function doubles each number, and map() applies this function to every element in the list.

reduce()

The reduce() function applies a rolling computation (a function) to elements of an iterable, reducing it to a single cumulative value. It’s part of the functools module.

It is commonly used for aggregating values (e.g., summing, multiplying, finding maximum).

Example:

from functools import reduce

numbers = [1, 2, 3, 4, 5]

# Calculate the product of all numbers
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 120Code language: Python (python)

In this example, the lambda function multiplies two numbers, and reduce() applies it iteratively, starting with the first two elements, then using the result with the next element.

19. What is the global keyword in a function?

Level: Intermediate

The global keyword is used to modify a global variable inside a function.

Example:

x = 10
def modify_global():
    global x
    x += 5

modify_global()
print(x)  # Output: 15Code language: Python (python)

20. What is a nonlocal variable in a function?

Level: Intermediate

The nonlocal keyword is used to modify a variable in the nearest enclosing scope that is not global.

Example:

def outer():
    x = 5
    def inner():
        nonlocal x
        x += 1
        print(x)
    inner()

outer()  # Output: 6Code language: Python (python)

This guide should prepare you for most interview questions on Python functions and modules. Practice coding these examples to solidify your understanding.

Conclusion

Mastering Python functions and modules is crucial for any aspiring Python developer. By understanding the questions and concepts discussed in this article, from defining functions and using arguments to creating and importing modules, you’ll be well-prepared to tackle interview questions and write robust Python code.

Remember that practice is key. Experiment with the examples provided, explore additional resources, and continue to build your understanding of Python’s powerful features. With dedication and consistent effort, you can confidently demonstrate your expertise in functions and modules, paving the way for success in your Python development journey.

Filed Under: Interview Questions, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Interview Questions Python Python Basics

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

Posted In

Interview Questions Python Python Basics
TweetF  sharein  shareP  Pin

  Python Interview Q&A

  • Python Interview
  • Beginner Python Interview Questions
  • Python Loops Interview Questions
  • Python String Interview Questions
  • Python Functions Interview Questions
  • Python List Interview Questions
  • Python OOP Interview Questions

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement