Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Functions in Python

Lesson 20 of 37 in the free Data Science notes on Siksha Sarovar, written by Rohit Jangra.

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 ?

BenefitDescription
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

SyntaxNameDescription
*argsPositional (tuple)Accepts any number of positional arguments
**kwargsKeyword (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 return is specified, the function returns None.
  • 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

ScopeDescriptionAccessible From
LocalDefined inside a functionOnly within that function
GlobalDefined outside all functionsAnywhere in the file
EnclosingIn an outer function (nested)Inner function can read it
Built-inPython's built-in namesEverywhere (print, len, etc.)

This is known as the LEGB Rule (Local → Enclosing → Global → Built-in).

---

Regular Function vs Lambda

FeatureRegular Function (def)Lambda Function
SyntaxMulti-lineSingle line
NameNamedAnonymous (usually)
ReturnExplicit returnImplicit (expression result)
ComplexityAny logicSimple expressions only
ReadabilityBetter for complex logicBetter for short operations
Use CaseGeneral-purposeCallbacks, 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:

FunctionDescriptionExample
map()Apply a function to every itemmap(str.upper, ["a", "b"])
filter()Keep items that satisfy a conditionfilter(lambda x: x > 0, [-1, 2, -3, 4])
reduce()Reduce a list to a single valuereduce(lambda a, b: a + b, [1, 2, 3]) → 6
sorted()Sort with custom keysorted(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(), and sorted() are higher-order functions commonly used in Data Science.
  • The LEGB rule determines variable scope resolution.