Functions in Python
Definition: A function is a reusable block of organized code that performs a specific task.Functions help break large programs into smaller, manageable, and reusable pieces.They follow the DRY principle — Don't Repeat Yourself.
---
Why Use Functions ?
| Benefit | Description |
|---|---|
| Reusability | Write once, use many times |
| Modularity | Break complex problems into smaller parts |
| Readability | Named functions make code self - documenting |
| Debugging | Easier to isolate and fix bugs |
| Testing | Individual functions can be unit tested |
---
Defining and Calling a Function
Syntax:
def function_name(parameters):
"""Docstring: Describes what the function does"""
# function body
return result
Example:
def greet(name):
"""Greets a person by name"""
return f"Hello, {name}!"
message = greet("Rahul")
print(message) # Hello, Rahul!
---
Types of Arguments
1. Positional Arguments
Arguments passed in the order they are defined.
def add(a, b):
return a + b
print(add(3, 5)) # 8
2. Keyword Arguments
Arguments passed by name, so order doesn't matter.
def info(name, age):
print(f"{name} is {age} years old")
info(age=21, name="Rahul") # Order doesn't matter
3. Default Arguments
Parameters with pre-assigned values. Used if no argument is provided.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Rahul")) # Hello, Rahul!
print(greet("Rahul", "Hi")) # Hi, Rahul!
4. Variable-Length Arguments
| Syntax | Name | Description |
|---|---|---|
*args | Positional (tuple) | Accepts any number of positional arguments |
**kwargs | Keyword (dict) | Accepts any number of keyword arguments |
def total(*args):
return sum(args)
print(total(1, 2, 3, 4, 5)) # 15
def display(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display(name="Rahul", age=21, city="Delhi")
---
Return Statement
- A function can return a value using
return. - If no
returnis specified, the function returnsNone. - A function can return multiple values as a tuple:
def min_max(numbers):
return min(numbers), max(numbers)
lo, hi = min_max([3, 1, 4, 1, 5, 9])
print(lo, hi) # 1 9
---
Lambda Functions (Anonymous Functions)
Definition: A lambda function is a small, anonymous function defined in a single line using the lambda keyword.
Syntax: lambda arguments: expression
Examples:
square = lambda x: x ** 2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 4)) # 7
Lambda with Built-in Functions:
# Sorting by second element
pairs = [(1, 3), (2, 1), (4, 2)]
pairs.sort(key=lambda x: x[1])
print(pairs) # [(2, 1), (4, 2), (1, 3)]
# Filter: Keep only even numbers
evens = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5]))
print(evens) # [2, 4]
# Map: Square each number
squares = list(map(lambda x: x**2, [1, 2, 3, 4]))
print(squares) # [1, 4, 9, 16]
---
Scope of Variables
| Scope | Description | Accessible From |
|---|---|---|
| Local | Defined inside a function | Only within that function |
| Global | Defined outside all functions | Anywhere in the file |
| Enclosing | In an outer function (nested) | Inner function can read it |
| Built-in | Python's built-in names | Everywhere (print, len, etc.) |
This is known as the LEGB Rule (Local → Enclosing → Global → Built-in).
---
Regular Function vs Lambda
| Feature | Regular Function (def) | Lambda Function |
|---|---|---|
| Syntax | Multi-line | Single line |
| Name | Named | Anonymous (usually) |
| Return | Explicit return | Implicit (expression result) |
| Complexity | Any logic | Simple expressions only |
| Readability | Better for complex logic | Better for short operations |
| Use Case | General-purpose | Callbacks, sorting keys, filter/map |
Higher-Order Functions
A higher-order function is a function that takes another function as an argument or returns one. Python's built-in higher-order functions:
| Function | Description | Example |
|---|---|---|
map() | Apply a function to every item | map(str.upper, ["a", "b"]) |
filter() | Keep items that satisfy a condition | filter(lambda x: x > 0, [-1, 2, -3, 4]) |
reduce() | Reduce a list to a single value | reduce(lambda a, b: a + b, [1, 2, 3]) → 6 |
sorted() | Sort with custom key | sorted(data, key=lambda x: x["age"]) |
Summary
- Functions promote reusability, modularity, and readability.
- Python supports positional, keyword, default, and variable-length arguments.
- Lambda functions are concise, one-line anonymous functions.
map(),filter(), andsorted()are higher-order functions commonly used in Data Science.- The LEGB rule determines variable scope resolution.