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


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.
Function | Description | Example |
abs() | Returns absolute value | abs(-7) → 7 |
all() | True if all elements are true | all([True, 1, 3]) → True |
any() | True if any element is true | any([False, 0, 5]) → True |
ascii() | Returns escaped string version | ascii('hiआ') → '\\u0939\\u093f\\u0906' |
bin() | Converts number to binary | bin(5) → '0b101' |
bool() | Converts to boolean | bool([]) → False |
chr() | Returns character from Unicode | chr(97) → 'a' |
ord() | Returns Unicode from character | ord('a') → 97 |
divmod() | Returns quotient & remainder | divmod(9, 2) → (4, 1) |
enumerate() | Adds counter to iterable | enumerate(['a','b']) → [(0,'a')] |
eval() | Executes string expression | eval("3+4") → 7 |
float() | Converts to float | float('5.4') → 5.4 |
format() | Formats a value | format(1234, ',') → '1,234' |
input() | Takes user input | input("Enter name: ") |
int() | Converts to integer | int('9') → 9 |
len() | Returns length of object | len("hello") → 5 |
max() | Returns maximum value | max(4, 9, 2) → 9 |
min() | Returns minimum value | min(4, 9, 2) → 2 |
pow() | Returns power | pow(2, 3) → 8 |
round() | Rounds value | round(3.1415, 2) → 3.14 |
sum() | Adds iterable elements | sum([1, 2, 3]) → 6 |
type() | Returns data type | type(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:
- Positional Arguments: Values passed to parameters based on their position.
def add(a, b):
return a + b
add(3, 5) # Output: 8
- 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")
- Default Arguments: Provide default values if no value is passed.
def welcome(name="Guest"):
print("Welcome,", name)
welcome() # Output: Welcome, Guest
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.
Subscribe to my newsletter
Read articles from Alisha Malhotra directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
