Functions and Lambda Expressions
Define Python functions, pass args, kwargs, return values, closures, nested scopes, and anonymous lambda expressions.
Downloaded from PrepIQ (https://prepiq.online)
Q1. What is a function in Python and what is function scope?
Function is reusable code block. Scope determines variable accessibility. Python has 4 scopes: Local, Enclosing, Global, Built-in (LEGB rule).
def greet(name):
message = f'Hello {name}' # Local
return message
global_var = 'global'
def show():
print(global_var) # Access global
show()
Q2. What are *args and **kwargs?
def add(*args):
return sum(args)
print(add(1, 2, 3)) # 6
def info(**kwargs):
for k, v in kwargs.items():
print(f'{k}: {v}')
info(name='John', age=30)
Q3. What is a lambda function?
square = lambda x: x ** 2
print(square(5)) # 25
# With map, filter, sorted
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
Q4. What is the mutable default argument trap?
# WRONG - shared default!
def append_to_list(item, my_list=[]):
my_list.append(item)
return my_list
print(append_to_list(1)) # [1]
print(append_to_list(2)) # [1, 2] NOT [2]!
# CORRECT - use None
def append_correct(item, my_list=None):
if my_list is None:
my_list = []
my_list.append(item)
return my_list
Q5. How do you return multiple values from a function?
def get_user():
name = 'John'
age = 30
email = 'john@gmail.com'
return name, age, email # Returns tuple
name, age, email = get_user()
print(name, age, email)
# Or return dict
def get_user2():
return {'name': 'John', 'age': 30}
Q6. What is a docstring and why is it important?
def add(a, b):
'''Add two numbers.
Args:
a: First number
b: Second number
Returns:
Sum of a and b
'''
return a + b
# Access docstring
print(add.__doc__)
help(add)
Q7. What is a decorator?
def my_decorator(func):
def wrapper():
print('Before')
func()
print('After')
return wrapper
@my_decorator
def say_hello():
print('Hello!')
say_hello()
# Output:
# Before
# Hello!
# After
Q8. What is a closure?
def make_multiplier(n):
def multiplier(x):
return x * n # Captures n
return multiplier
multiply_by_2 = make_multiplier(2)
print(multiply_by_2(5)) # 10
multiply_by_3 = make_multiplier(3)
print(multiply_by_3(5)) # 15
Q9. What are function annotations?
def add(a: int, b: int) -> int:
'''Add two integers.'''
return a + b
print(add.__annotations__)
# {'a': int, 'b': int, 'return': int}
from typing import List
def process(items: List[int]) -> int:
return sum(items)
Q10. What are map, filter, and reduce?
from functools import reduce
# map - apply function to each element
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, nums))
# [1, 4, 9, 16, 25]
# filter - select matching elements
evens = list(filter(lambda x: x % 2 == 0, nums))
# [2, 4]
# reduce - accumulate values
product = reduce(lambda x, y: x * y, nums)
# 120
Functions and Lambda Expressions
Define Python functions, pass args, kwargs, return values, closures, nested scopes, and anonymous lambda expressions.
What is a function in Python and what is function scope?
Function is reusable code block. Scope determines variable accessibility. Python has 4 scopes: Local, Enclosin...
What are *args and **kwargs?
def add(*args): return sum(args) print(add(1, 2, 3)) # 6 def info(**kwargs): for k, v in kwargs.ite...
What is a lambda function?
square = lambda x: x ** 2 print(square(5)) # 25 # With map, filter, sorted nums = [1, 2, 3, 4, 5] squared =...
What is the mutable default argument trap?
# WRONG - shared default! def append_to_list(item, my_list=[]): my_list.append(item) return my_list p...
How do you return multiple values from a function?
def get_user(): name = 'John' age = 30 email = 'john@gmail.com' return name, age, email # Ret...
What is a docstring and why is it important?
def add(a, b): '''Add two numbers. Args: a: First number b: Second number...
What is a decorator?
def my_decorator(func): def wrapper(): print('Before') func() print('After') r...
What is a closure?
def make_multiplier(n): def multiplier(x): return x * n # Captures n return multiplier multi...
What are function annotations?
def add(a: int, b: int) -> int: '''Add two integers.''' return a + b print(add.__annotations__) # {'a...
What are map, filter, and reduce?
from functools import reduce # map - apply function to each element nums = [1, 2, 3, 4, 5] squared = list(map...