def (Function)
def is used to define a function in Python. A function is a reusable block of code that performs a
specific task. It helps reduce repetition and makes code modular and easy to manage.
def greet():
print("Hello, welcome!")
greet()
1. args (Arbitrary Arguments)
*args allows you to pass a variable number of positional arguments to a function. It is useful
when you don’t know how many inputs the function will receive.
def add_numbers(*args):
total = 0
for num in args:
total += num
print(total)
add_numbers(1, 2, 3, 4)
2. kwargs (Keyword Arguments)
**kwargs allows you to pass a variable number of keyword arguments (key-value pairs) to a
function. It is useful for flexible and dynamic data handling.
def greet():
print("Hello, welcome!")
greet()
3. Nested def (Function inside Function)
A nested function is a function defined inside another function. It is useful for encapsulation and
when a helper function is needed only inside a specific function.
def outer():
def inner():
print("Inside inner function")
inner()
outer()
4. try, except, finally
these are used for exception handling.
try → code that may cause error
except → handles the error
finally → always executes (whether error occurs or not)
try:
num = int(input("Enter number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution completed")
5. Lambda Function
A lambda function is a small anonymous function defined in a single line using the lambda
keyword. It is used for short, simple operations.
square = lambda x: x * x
print(square(5))
6. sorted() with Lambda
sorted() is used to sort data, and lambda can define custom sorting logic.
students = [("A", 90), ("B", 75), ("C", 85)]
sorted_data = sorted(students, key=lambda x: x[1])
print(sorted_data)
7. map() with Lambda
map() applies a function to all elements in a sequence. Lambda is often used for quick
transformations
numbers = [1, 2, 3, 4]
result = list(map(lambda x: x * 2, numbers))
print(result)
8. reduce() with Lambda
reduce() applies a function cumulatively to elements of a sequence to produce a single result.
It is part of the functools module.
from functools import reduce
numbers = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, numbers)
print(result)
9. Lambda inside def
A lambda function can be used inside a normal function (def) to perform small operations
dynamically.
def multiply(n):
return lambda x: x * n
double = multiply(2)
print(double(5))
one liners
def → define function
*args → multiple positional arguments
**kwargs → multiple keyword arguments
nested def → function inside function
try-except-finally → error handling
lambda → one-line function
sorted + lambda → custom sorting
map + lambda → apply function to list
reduce + lambda → cumulative result
lambda inside def → dynamic function