This comprehensive guide addresses the key interview questions and answers related to Python functions, designed to assist you in your preparation for technical interviews.
Basic Function Questions
1. What is a function in Python?
A function is a segment of code that can be reused and is designed to execute a particular operation. Utilizing functions aids in structuring code, enhances its clarity, and minimizes redundancy.
Example:
def greet(name):
return f"Hello, {name}!"
result = greet("Alice")
print(result)
Output:
Hello, Alice!
1.How do you define a function in Python?
Functions are established with the def keyword, succeeded by the function's name, a set of parameters enclosed in parentheses, and a colon. The body of the function is then indented.
Syntax:
def function_name(parameters):
# function body
return value
1.What is the difference between parameters and arguments?
- Parameters are variables listed in the function definition
- Arguments are actual values passed to the function when calling it
Example:
def add(a, b): # a and b are parameters
return a + b
result = add(5, 3) # 5 and 3 are arguments
### 1. What is a return statement?What is a return statement?
The return statement allows a function to terminate and, if desired, return a value to the invoking function. In the absence of a return statement, a function will return None.
Example:
def square(n):
return n * n
def print_message():
print("Hello")
# no return statement, returns None
result1 = square(4) # 16
result2 = print_message() # None
Function Types
### 1. What are different types of functions in Python?What are different types of functions in Python?
- Built-in functions:
print,len,type - User-defined functions: Created using
def - Lambda functions: Anonymous one-line functions
- Recursive functions: Functions that call themselves
6. What is a lambda function?
A lambda function refers to a compact anonymous function that is created using the lambda keyword. It may accept multiple parameters; however, it is restricted to a single expression.
Example:
# Regular function
def add(x, y):
return x + y
# Lambda function
add_lambda = lambda x, y: x + y
print(add(5, 3)) # 8
print(add_lambda(5, 3)) # 8
7. What is a recursive function?
A recursive function is defined as one that invokes itself during its execution. It is essential for such a function to include a base case, which serves as a stopping condition for the recursion process.
Example:
def factorial(n):
if n == 0 or n == 1: # base case
return 1
return n * factorial(n - 1) # recursive call
print(factorial(5)) # 120
Function Arguments
8. What are default arguments?
Default parameters are assigned preset values within the function definition. If a value is not supplied when the function is invoked, the preset value will be utilized.
Example:
def greet(name, message="Hello"):
return f"{message}, {name}!"
print(greet("Alice")) # Hello, Alice!
print(greet("Bob", "Good morning")) # Good morning, Bob!
9. What are keyword arguments?
Keyword arguments are provided by clearly specifying the parameter name together with its corresponding value. This feature enables the arguments to be supplied in any sequence.
Example:
def describe_person(name, age, city):
print(f"{name} is {age} years old and lives in {city}")
describe_person(age=25, name="Alice", city="New York")
10. What is *args in Python?
*args enables a function to receive an arbitrary quantity of positional arguments, which are collected into a tuple.
Example:
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(10, 20, 30, 40)) # 100
11. What is **kwargs in Python?
**kwargs enables a function to receive an arbitrary number of keyword arguments, encapsulating them within a dictionary.
Example:
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
Output:
name: Alice
age: 25
city: New York
Advanced Concepts
12. What is a decorator in Python?
A decorator is a type of function that alters the functionality of another function. It is utilized in conjunction with the @ symbol.
Example:
def uppercase_decorator(func):
def wrapper():
result = func()
return result.upper()
return wrapper
@uppercase_decorator
def greet():
return "hello"
print(greet()) # HELLO
13. What is function scope?
Function scope pertains to the accessibility of variables. Variables that are declared within a function are considered local and cannot be accessed from outside that function.
Example:
x = 10 # global variable
def my_function():
y = 5 # local variable
print(x) # can access global
print(y)
my_function()
# print(y) # Error: y is not defined
14. What is the difference between global and local variables?
- Local variables: Defined inside a function, accessible only within that function
- Global variables: Defined outside all functions, accessible throughout the program
Example:
count = 0 # global
def increment():
global count
count += 1
increment()
print(count) # 1
15. What is a closure in Python?
A closure is defined as a function that retains access to the variables from its surrounding context, even after the execution of the outer function has been completed.
Example:
def outer(x):
def inner(y):
return x + y
return inner
add_5 = outer(5)
print(add_5(3)) # 8
print(add_5(10)) # 15
Practical Questions
16. How do you pass a function as an argument?
In Python, functions are treated as first-class citizens, meaning they can be utilized as arguments for other functions.
Example:
def apply_operation(func, x, y):
return func(x, y)
def add(a, b):
return a + b
def multiply(a, b):
return a * b
print(apply_operation(add, 5, 3)) # 8
print(apply_operation(multiply, 5, 3)) # 15
17. What is the difference between return and print?
-
returnsends a value back to the caller and exits the function -
printdisplays output but doesn't return a value
Example:
def func1():
return 10
def func2():
print(10)
x = func1() # x = 10
y = func2() # prints 10, but y = None
18. Can a function return multiple values?
Indeed, functions have the capability to return more than one value by encapsulating them within a tuple.
Example:
def get_stats(numbers):
return min(numbers), max(numbers), sum(numbers)
minimum, maximum, total = get_stats([1, 2, 3, 4, 5])
print(f"Min: {minimum}, Max: {maximum}, Sum: {total}")
19. What is a generator function?
A generator function employs yield as opposed to return, yielding values incrementally, which conserves memory usage.
Example:
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for num in count_up_to(5):
print(num)
20. What is the purpose of the pass statement in functions?
The pass statement serves as a placeholder that performs no action. It is utilized in situations where a function is syntactically necessary, yet you are not ready to implement its functionality at that moment.
Example:
def future_feature():
pass # will implement later
future_feature() # runs without error
Common Interview Patterns
21. Write a function to check if a number is prime
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(17)) # True
print(is_prime(20)) # False
22. Write a function to reverse a string
def reverse_string(text):
return text[::-1]
print(reverse_string("hello")) # olleh
23. Write a function to find the largest element in a list
def find_largest(numbers):
if not numbers:
return None
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
return largest
print(find_largest([3, 7, 2, 9, 1])) # 9
24. Write a function to count vowels in a string
def count_vowels(text):
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
return count
print(count_vowels("Hello World")) # 3
25. Write a function to check if a string is palindrome
def is_palindrome(text):
text = text.lower().replace(" ", "")
return text == text[::-1]
print(is_palindrome("racecar")) # True
print(is_palindrome("hello")) # False
Best Practices
Tips for Writing Good Functions:
1.
- Ensure functions are concise and specific - Every function ought to perform a single task effectively.
- Utilize meaningful names - The names of functions must accurately convey their functionality.
- Provide documentation for your functions - Implement docstrings to clarify the function's objectives, parameters, and return outputs.
- Steer clear of side effects - Functions should refrain from altering any global state.
- Employ early returns - Exit functions immediately once the outcome is determined.
Example of well-documented function:
def calculate_average(numbers):
"""
Calculate the average of a list of numbers.
Parameters:
numbers (list): List of numeric values
Returns:
float: Average of the numbers
"""
if not numbers:
return 0
return sum(numbers) / len(numbers)
Summary
Grasping the concept of functions in Python is crucial for developing clean and reusable code. Engage with these principles and patterns to excel in your technical interviews.