🧠 Blog 4 – Understanding Functions in Python: A Complete Guide

Alisha MalhotraAlisha Malhotra
5 min read

Introduction: What Are Functions?

In programming, a function is a block of organized and reusable code used to perform a single, related action. Functions help break our program into smaller and modular chunks, making it more readable, manageable, and efficient.

A function can take inputs (called parameters), perform operations, and return a result. Think of it as a machine: you give it ingredients (inputs), it processes them, and gives you the final product (output).


Advantages of Using Functions

  • Code Reusability – Write once, call multiple times.

  • Modularity – Break code into smaller, independent blocks.

  • Maintainability – Easier to update or debug specific tasks.

  • Improved Readability – Cleaner and more logical code structure.

  • Efficiency – Saves time and effort when working on large codebases.


Classification of Functions


1. Built-in Functions in Python

Python provides numerous built-in functions that simplify basic operations and are readily available for use.

FunctionDescriptionExample
abs()Returns absolute valueabs(-7) → 7
all()True if all elements are trueall([True, 1, 3]) → True
any()True if any element is trueany([False, 0, 5]) → True
ascii()Returns escaped string versionascii('hiआ') → '\\u0939\\u093f\\u0906'
bin()Converts number to binarybin(5) → '0b101'
bool()Converts to booleanbool([]) → False
chr()Returns character from Unicodechr(97) → 'a'
ord()Returns Unicode from characterord('a') → 97
divmod()Returns quotient & remainderdivmod(9, 2) → (4, 1)
enumerate()Adds counter to iterableenumerate(['a','b']) → [(0,'a')]
eval()Executes string expressioneval("3+4") → 7
float()Converts to floatfloat('5.4') → 5.4
format()Formats a valueformat(1234, ',') → '1,234'
input()Takes user inputinput("Enter name: ")
int()Converts to integerint('9') → 9
len()Returns length of objectlen("hello") → 5
max()Returns maximum valuemax(4, 9, 2) → 9
min()Returns minimum valuemin(4, 9, 2) → 2
pow()Returns powerpow(2, 3) → 8
round()Rounds valueround(3.1415, 2) → 3.14
sum()Adds iterable elementssum([1, 2, 3]) → 6
type()Returns data typetype(10) → <class 'int'>

2. User-Defined Functions

These are functions created by users to perform specific operations.

Syntax:

def greet(name):
    print("Hello,", name)

Calling the Function:

greet("Alisha")  # Output: Hello, Alisha

Types of Function Arguments

Python functions support multiple ways to pass arguments:

  1. Positional Arguments: Values passed to parameters based on their position.
def add(a, b):
    return a + b
add(3, 5)  # Output: 8
  1. Keyword Arguments: Use parameter names while calling, so order doesn't matter.
def intro(name, age):
    print(f"{name} is {age} years old")
intro(age=20, name="Riya")
  1. Default Arguments: Provide default values if no value is passed.
def welcome(name="Guest"):
    print("Welcome,", name)
welcome()  # Output: Welcome, Guest
  1. Variable-Length Arguments:

    • Positional *args: Accepts any number of positional arguments.

        def total(*args):
            return sum(args)
        total(1, 2, 3)  # Output: 6
      
    • Keyword **kwargs: Accepts any number of keyword arguments.

        def profile(**kwargs):
            print(kwargs)
        profile(name="Riya", age=21)
      

Order of Arguments in Function Definition:

Positional, variable_positional, keyword=”value”, ** variable_keyword


Docstrings and First-Class Functions

  • Docstring: Describes purpose of the function.

      def square(x):
          """Returns square of x"""
          return x*x
      print(square.__doc__)
    
  • First-Class Objects – Functions in Python can be:

    • Assigned to variables:

        def greet(): return "Hi"
        say_hi = greet
        print(say_hi())
      
    • Passed as arguments:

        def shout(text): return text.upper()
        def call(func): return func("hello")
        print(call(shout))  # Output: HELLO
      
    • Returned from another function (nested):

        def outer():
            def inner():
                return "Inner function"
            return inner
        result = outer()
        print(result())
      

Iterative vs Recursive Functions

  • Iterative: Repeats a task using loops.
def factorial_iter(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result
  • Recursive: Function calls itself until base condition.
def factorial_rec(n):
    if n == 1:
        return 1
    return n * factorial_rec(n - 1)

Key Difference:

  • Iteration uses loops, better for memory.

  • Recursion is elegant but deeper calls may lead to stack overflow.


Anonymous Functions: Lambda

  • lambda creates small unnamed functions in one line.

  • Syntax: lambda arguments: expression

square = lambda x: x * x
print(square(4))  # Output: 16

Useful with functions like map(), filter():

nums = [1, 2, 3, 4]
squares = list(map(lambda x: x*x, nums))
print(squares)  # [1, 4, 9, 16]

Use when:

  • Function logic is small.

  • You don’t want to define a named function.


Summary

In this blog, we explored the concept of functions in Python, from built-in tools to creating your own. You learned how to pass different types of arguments, how functions are first-class citizens, and the difference between iteration and recursion. We also explored lambda functions and their practical use cases.

Functions help us write cleaner, reusable, and modular code. Mastering them is essential to becoming a confident Python developer.


My Experience

Initially, I found lambda functions quite confusing. I couldn’t understand why they existed if we already had regular functions. I used to skip them until I saw how map(), filter(), and short expressions become so concise using lambdas.

It clicked for me when I used it inside a list comprehension and realized how elegant and powerful it is for writing one-time, quick utility functions without the need to name them.


Coming Up Next

We’ll now move toward applying functions to data structures. Here’s a teaser:

def list_summary(my_list):
    return {
        "length": len(my_list),
        "max": max(my_list),
        "min": min(my_list)
    }

print(list_summary([3, 7, 2, 9]))

In the next post, we’ll explore how functions interact with Lists, Tuples, Dictionaries, and Sets smartly and efficiently.

0
Subscribe to my newsletter

Read articles from Alisha Malhotra directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Alisha Malhotra
Alisha Malhotra