Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 01

Python Functions — Complete Module Overview

Master Python functions from scratch: definition, parameters, scope, lambda, and special functions filter/map/reduce with real examples and quizzes.

Intermediate5 hours
Python functions module — 5 hour path from beginner to intermediate

What you will learn

  • Why functions exist — write once, call many times
  • Definition vs call, and the Input → Process → Output model
  • The 4 ways to write functions
  • Parameters vs arguments, plus a preview of the 5 argument types
  • The rest of this module: scope, return, lambda, filter / map / reduce

Learn Python functions the way experienced developers do — through visuals, mental models, code, and practice, not by memorizing syntax.

Why Functions Matter

Imagine you're building a calculator. Without functions, you'd rewrite the same logic every time.

❌ Without functions — repetitive, hard to maintain:

python
c1 = 10 + 20
c2 = 30 + 40
c3 = 50 + 60
# Same logic, written again and again...

✅ With functions — write once, reuse forever:

python
def add(x, y):
    return x + y

print(add(10, 20))   # 30
print(add(30, 40))   # 70
print(add(50, 60))   # 110

Definition: A function is a named block of reusable code that performs a specific task and runs only when it is called.


5 Advantages of Using Functions

Advantage What it means
Less development time Write logic once, reuse anywhere
Less memory space One copy of code lives in memory
Less execution time No redundant processing
Enhanced performance Smaller, focused units run faster
Minimized redundancy No copy-paste code across the program

Learning Roadmap

Rather than jumping into syntax, follow this progression — each lesson builds on the previous one:

Python Functions learning roadmap: Function Basics → Parameters → Scope → Return → Lambda → Map/Filter/Reduce
# Lesson Key concepts Time
2 Function Approaches Definition · Call · 4 approaches · IPO model 40 min
3 Parameters and Arguments Positional · Default · Keyword · *args · **kwargs 60 min
4 Local and Global Variables Scope · global keyword · globals() 40 min
5 The return Statement Explicit · Implicit · Multiple return values 30 min
6 Lambda Functions Anonymous functions · inline operations 40 min
7 Special Functions filter() · map() · reduce() 50 min

6 lessons · 30+ concepts · 60+ quiz questions


The Anatomy of a Function

Every Python function has exactly two essential parts — no more, no less.

Anatomy of a Python function: definition box and call box connected by dashed line

🔑 Golden rule: Writing def creates the function but does not execute it. Execution begins only when you call it.

python
def greet(name):         # ← DEFINITION (registered, not run)
    return f"Hello, {name}!"

print(greet("Alice"))    # ← CALL (execution starts here)
print(greet("Bob"))      # ← another call — same definition

How a Function Thinks — Input → Process → Output

Every function follows the same three-stage lifecycle. This mental model is more useful than memorizing syntax — it applies to every function you will ever write.

Python function IPO model: INPUT box → arrow → PROCESS box → arrow → OUTPUT box
python
def add(a, b):      # INPUT  — a, b received from call
    c = a + b       # PROCESS — computation inside body
    return c        # OUTPUT  — result sent back to caller

The 4 Ways to Write Functions

Python functions are written in four different styles depending on where input comes from and where output goes.

Four function styles: parameters return, input print, parameters print, input return

1 — Parameters → Return (Most common)

Best for reusable programs and interviews.

python
def square(x):
    return x * x

result = square(5)   # result = 25
print(result)

2 — Input Inside → Print Inside

Useful for self-contained, interactive scripts.

python
def greet():
    name = input("Your name: ")
    print(f"Hello, {name}!")

greet()   # handles input AND output internally

3 — Parameters → Print Inside

Accepts data from outside but prints the result internally.

python
def show_square(n):
    print(f"Square of {n} = {n*n}")

show_square(7)   # Square of 7 = 49

4 — Input Inside → Return

Collects its own data but lets the caller decide what to do with the result.

python
def get_cube():
    n = int(input("Enter a number: "))
    return n ** 3

val = get_cube()
print("Cube =", val)
Approach Input source Output destination
1 Function call (params) return to caller
2 input() inside body print() inside body
3 Function call (params) print() inside body
4 input() inside body return to caller

Parameters vs Arguments

This is one of the most confused topics for beginners. The diagram below makes it clear.

Parameters vs Arguments: definition side shows parameters, call side shows arguments
Term Where Role
Parameter Function heading — def f(a, b) Placeholder variable that receives data
Argument Function call — f(10, 20) The actual value sent to the function
python
def greet(name):      # name → parameter (placeholder)
    print(name)

greet("Mahesh")       # "Mahesh" → argument (actual value)

Five Types of Arguments — Visual Cheat Sheet

Five argument types: positional, default, keyword, star args, star-star kwargs
Type Syntax What it does
Positional f(10, 20) Matched by position left → right
Default def f(x, n=10) Pre-set value used when caller skips it
Keyword f(b=20, a=10) Named — order doesn't matter
*args def f(*vals) Any number of positional args → tuple
**kwargs def f(**info) Any number of keyword args → dict
python
def profile(name, age=18, *skills, **extra):
    print(name)
    print(age)
    print(skills)
    print(extra)

profile(
    "Mahesh",
    24,
    "Python",
    "AI",
    city="Hyderabad"
)
Part Value
name "Mahesh"
age 24
skills (*args) ("Python", "AI")
extra (**kwargs) {"city": "Hyderabad"}

Syntax reference

python
def functionname(param1, param2, *varlen, default=value, **kwargs):
    """Optional docstring"""
    # body
    return result    # optional
Part Role
def Starts the function definition
functionname Any valid Python identifier
param1, param2 Formal (positional) parameters
*varlen Variable-length args → tuple
default=value Default parameter
**kwargs Keyword variable-length → dict
return Exits and sends back a value

Prerequisites

Before starting this module, make sure you are comfortable with:

Loading playground…

Check your understanding

Functions overview quiz

Why do we use functions instead of repeating the same addition lines (c1 = 10+20, c2 = 30+40)?

1 / 10