Python November 01 ,2025

Functions in Python 

Table of Contents
  1. What is a Function?
  2. Function Syntax
  3. Types of Functions in Python
      a. Built-in Functions
      b. User-defined Functions
  4. Function Parameters and Arguments
  5. Return Statement
  6. Docstrings
  7. Scope and Lifetime of Variables
  8. Lambda (Anonymous) Functions
  9. Recursive Functions
  10. Function Nesting (Inner Functions)
  11. Function as Object
  12. Decorators
  13. Conclusion

1. What is a Function?

A function in Python is a block of organized, reusable code that is used to perform a specific task.
Instead of writing the same code multiple times, you can define a function once and call it whenever needed.

Functions make code:

  • Modular (divided into logical parts)
  • Reusable (can be used multiple times)
  • Readable and maintainable

Example:

def greet():
    print("Hello, welcome to Python!")

Here:

  • def → keyword to define a function.
  • greet → function name.
  • () → parentheses for parameters (none here).
  • : → indicates the start of the function block.
  • print() → body (indented code) of the function.

To call this function:

greet()

Output:

Hello, welcome to Python!

2. Function Syntax

def function_name(parameters):
    """optional docstring"""
    # function body
    return value

Explanation:

PartDescription
defKeyword used to define a function
function_nameIdentifier for the function
parametersInput values (optional)
docstringOptional string describing the function’s purpose
returnUsed to send a value back to the caller

Example with Return Statement

def add(a, b):
    """This function returns the sum of two numbers."""
    return a + b

result = add(5, 7)
print(result)

Output:

12

3. Types of Functions in Python

Functions in Python are a fundamental building block of programming. They help you organize code, avoid repetition, and improve readability.
Broadly, Python functions can be classified into two main categories:

(a) Built-in Functions

Built-in functions are predefined functions that come packaged with Python itself.
They are always available for use without needing to import any external module. These functions perform a wide range of tasks like mathematical calculations, data type conversions, string manipulations, and input/output operations.

In other words, they are ready-to-use utility tools that save you from rewriting common operations.

Examples of Common Built-in Functions

FunctionDescriptionExampleOutput
print()Displays output on the consoleprint("Hello")Hello
len()Returns length of a sequence (string, list, etc.)len("Python")6
type()Returns the type of an objecttype(10) 
range()Generates a sequence of numbersrange(5)0,1,2,3,4
input()Takes input from the userinput("Enter:")
max()Returns the largest valuemax([3,8,1])8
min()Returns the smallest valuemin([3,8,1])1
sum()Returns the sum of items in an iterablesum([1,2,3])6
sorted()Returns a sorted listsorted([3,1,2])[1,2,3]
abs()Returns absolute value of a numberabs(-5)5
round()Rounds a number to nearest integer or given precisionround(3.456, 2)3.46

How Built-in Functions Work

Python defines these functions in its standard library (builtins module).
When you call a built-in function like print() or len(), Python does not need you to import anything, because they are automatically loaded when the interpreter starts.

Example:

numbers = [10, 20, 30]
print(sum(numbers))   # 60
print(len(numbers))   # 3

Explanation:

  1. The list [10, 20, 30] is passed to the built-in function sum().
  2. sum() iterates through the list and adds all elements (10 + 20 + 30 = 60).
  3. len() returns the number of elements (3).

Output:

60
3

Key Advantages of Built-in Functions

  • Pre-tested and reliable: You can trust them because they are implemented by Python developers and tested thoroughly.
  • Save development time: You don’t need to write common operations manually.
  • Optimized performance: They are implemented in C internally, so they’re faster than equivalent Python code.
  • Always available: No need to import modules to use them.

Additional Built-in Functions (Advanced Examples)

Python has over 60 built-in functions. Some more commonly used include:

FunctionDescriptionExample
any()Returns True if any element of iterable is Trueany([0,1,0]) → True
all()Returns True if all elements of iterable are Trueall([1,1,1]) → True
zip()Combines two or more iterables element-wiselist(zip([1,2],[‘a’,‘b’])) → [(1,'a'),(2,'b')]
map()Applies a function to all items in an iterablelist(map(str, [1,2,3])) → ['1','2','3']
filter()Filters elements based on a conditionlist(filter(lambda x: x>2,[1,2,3,4])) → [3,4]
dir()Lists all attributes/methods of an objectdir(str)
help()Displays documentation of a function or modulehelp(print)

These functions form the core of Python programming — they’re the foundation of almost every script.

(b) User-defined Functions

Definition

User-defined functions are those that you create yourself to perform a specific task.
They allow you to structure your program into reusable blocks of logic.

When your code grows larger, repeating logic in multiple places becomes inefficient. Functions let you encapsulate that logic and call it whenever needed.

Creating a User-defined Function

In Python, a function is defined using the def keyword.

Syntax:

def function_name(parameters):
    """optional docstring"""
    # body of function
    return value

Explanation of Syntax:

  • def – Keyword used to declare a function.
  • function_name – The identifier used to call the function later.
  • parameters – Optional. Variables that receive values when the function is called.
  • """docstring""" – A description of what the function does (optional but recommended).
  • Function Body – Contains the code to execute when the function is called.
  • return – Optional. Sends back a result to the caller.

Example:

def multiply(x, y):
    """This function multiplies two numbers and returns the result."""
    return x * y

print(multiply(3, 5))

Output:

15

Detailed Explanation:

  1. The def keyword starts the function definition.
  2. multiply is the function’s name.
  3. It takes two parameters x and y.
  4. The function body calculates the product using x * y.
  5. The return statement sends the computed value back.
  6. When we call multiply(3, 5), Python executes the body and returns 15.

Key Components of User-defined Functions

ComponentDescriptionExample
Function DefinitionThe block of code that defines what the function does.def greet(): print("Hello!")
Function CallThe statement that executes the function.greet()
ParametersValues the function accepts as input.def add(a,b)
ArgumentsActual values passed to the function when it is called.add(5,10)
Return StatementSends result back to the calling point.return a+b

Example with Parameters and Return Value

def add_numbers(a, b):
    result = a + b
    return result

sum_result = add_numbers(4, 7)
print("Sum:", sum_result)

Output:

Sum: 11

Explanation:

  • The values 4 and 7 are arguments passed to a and b.
  • Inside the function, they are added and returned.
  • The returned value is stored in sum_result.

User-defined Function Without Parameters

You can also define functions that take no parameters.

def greet():
    print("Welcome to Python Functions!")

greet()

Output:

Welcome to Python Functions!

User-defined Function Without Return Value

A function doesn’t always need to return something; it can just perform an action.

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

show_message("Alice")

Output:

Hello, Alice

User-defined Function With Default Parameters

You can assign default values to parameters. If no value is provided during the call, the default will be used.

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

greet()           # uses default
greet("Saumya")   # overrides default

Output:

Hello, Guest
Hello, Saumya

User-defined Function With Keyword Arguments

You can call a function using named arguments, making code more readable.

def intro(name, age):
    print("Name:", name)
    print("Age:", age)

intro(age=25, name="John")

Output:

Name: John
Age: 25

Benefits of User-defined Functions

  • Reusability: Once written, a function can be reused multiple times.
  • Modularity: Large programs can be split into smaller, manageable parts.
  • Readability: Code becomes easier to understand.
  • Debugging: Easier to test smaller parts individually.
  • Scalability: New features can be added without changing the entire program.

Built-in vs. User-defined Functions — Comparison

FeatureBuilt-in FunctionUser-defined Function
DefinitionProvided by PythonCreated by the user
AvailabilityAlways availableDefined when needed
Examplesprint(), len(), sum()def add(a,b): return a+b
PurposePerform common predefined tasksPerform custom or specific tasks
Import Required?NoNo, but user must define before calling

4. Function Parameters and Arguments

Parameters:

Parameters are variables declared inside the parentheses of a function definition. They act as placeholders that define what kind of data the function expects when it is called. Parameters allow a function to accept input values without knowing them in advance. When the function runs, these parameters hold the data that is passed to it, which can then be used within the function body.

In simple terms, parameters make a function flexible and reusable, because you can pass different values each time you call the same function. Without parameters, a function would always perform the same operation on fixed data.

Arguments:

Arguments are the actual values that are passed into a function when it is called. These values are assigned to the parameters defined in the function header. Arguments provide the real input data that the function will work on during its execution.

Each time you call the function, you can provide different arguments, allowing the same function to behave differently based on the input. This makes your program more dynamic and interactive.

Example:

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

greet("Alice")

Output:

Hello Alice

Types of Function Arguments in Python

A. Positional Arguments

Positional arguments are the most common type.
They are matched by order (position) when you call the function.

That means the first argument goes to the first parameter,
the second argument to the second parameter, and so on.

Syntax Example:

def student_info(name, age):
    print("Name:", name)
    print("Age:", age)

student_info("John", 20)

Output:

Name: John
Age: 20

Explanation:

  • The first argument "John" is assigned to parameter name.
  • The second argument 20 is assigned to parameter age.

⚠️ Order Matters!

If you change the order, you change the meaning:

student_info(20, "John")

Output:

Name: 20
Age: John

Here, the arguments are swapped, causing a logical error — no syntax error, but wrong meaning.

Key Rule:

Positional arguments are assigned in the exact order they appear.

B. Keyword Arguments

In keyword arguments, you explicitly specify which parameter each value belongs to — by using the parameter name in the call.

This gives clarity and flexibility — you don’t have to remember the order.

Syntax Example:

def student_info(name, age):
    print("Name:", name)
    print("Age:", age)

student_info(age=20, name="John")

Output:

Name: John
Age: 20

Explanation:

  • Python matches arguments by name, not by order.
  • Even though age is written before name, Python correctly assigns them because of the names.

Advantages:

  1. Improves readability (you know what each value means).
  2. Avoids confusion due to argument order.
  3. Useful in functions with many parameters.

Example:

def show_profile(name, age, country, hobby):
    print(f"{name}, {age} years old, from {country}, loves {hobby}.")

show_profile(hobby="Reading", country="India", name="Alice", age=23)

Output:

Alice, 23 years old, from India, loves Reading.

C. Default Arguments

Concept:

Sometimes, you want a function parameter to have a default value,
so if no argument is passed, Python automatically uses that default.

These are called default arguments.

Syntax Example:

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

greet()         # no argument passed
greet("Alex")   # argument passed

Output:

Hello Guest
Hello Alex

Explanation:

  • In the first call, no argument is given → uses default "Guest".
  • In the second call, "Alex" overrides the default.

Advantages:

  • Makes parameters optional.
  • Avoids errors if arguments are missing.
  • Reduces the need for function overloading (unlike Java/C++).

 Rules for Default Arguments:

  1. Default arguments must come after non-default arguments in the function definition.

Correct:

def display(name, age=18):
    print(name, age)

Incorrect:

def display(age=18, name):  # SyntaxError
    print(name, age)
  1. You can combine default, positional, and keyword arguments — but maintain order carefully.

D. Variable-length Arguments

Concept:

Sometimes you don’t know in advance how many arguments will be passed.
For such cases, Python provides variable-length arguments using two special symbols:

SymbolMeaningType
*argsFor non-keyword (positional) variable argumentsTuple
**kwargsFor keyword variable argumentsDictionary

1️⃣ Using *args (Non-keyword Arguments)

  • Collects any number of positional arguments into a tuple.
  • The function can then iterate or process them.

Syntax Example:

def add_numbers(*args):
    total = 0
    for num in args:
        total += num
    return total

print(add_numbers(1, 2, 3, 4))

Output:

10

Explanation:

  • *args collects all given numbers (1, 2, 3, 4) into a tuple.
  • The function loops through them and sums them up.

You Can Pass Any Number of Arguments:

print(add_numbers(5))
print(add_numbers(10, 20, 30))

Output:

5
60

2️⃣ Using **kwargs (Keyword Arguments)

  • Collects variable number of keyword arguments (key=value pairs).
  • Stores them in a dictionary.

Syntax Example:

def show_details(**kwargs):
    for key, value in kwargs.items():
        print(key, ":", value)

show_details(name="Alice", age=25, city="Delhi")

Output:

name : Alice
age : 25
city : Delhi

Explanation:

  • All keyword arguments are packed into a dictionary:

    {'name': 'Alice', 'age': 25, 'city': 'Delhi'}
    
  • Then you can iterate through them easily.

Practical Example — Combining *args and **kwargs

def profile(*args, **kwargs):
    print("Positional:", args)
    print("Keyword:", kwargs)

profile("Saumya", 22, city="Delhi", hobby="Coding")

Output:

Positional: ('Saumya', 22)
Keyword: {'city': 'Delhi', 'hobby': 'Coding'}

Explanation:

  • Positional arguments → stored in a tuple (*args)
  • Keyword arguments → stored in a dictionary (**kwargs)

Rules When Combining All Argument Types

When defining functions that use all argument types, the order must be:

1. Positional arguments
2. *args
3. Keyword-only arguments (optional)
4. **kwargs

Example:

def demo(a, b, *args, **kwargs):
    print(a, b)
    print(args)
    print(kwargs)

demo(1, 2, 3, 4, x=10, y=20)

Output:

1 2
(3, 4)
{'x': 10, 'y': 20}

 

5. Return Statement 

The return statement is used in a function to send a value or result back to the part of the program where the function was called.
When Python encounters a return statement inside a function, it immediately stops executing the function and sends the specified value back to the caller.
This allows functions to produce outputs that can be stored in variables or used in further calculations.
If a function does not include a return statement, it automatically returns None by default, meaning it doesn’t produce a meaningful output.
Using return makes a function more powerful and reusable since it can compute and provide results instead of only performing actions like printing.

Example:

def square(num):
    return num ** 2

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

6. Docstrings (Documentation Strings) 

Docstrings are special strings written just below a function, class, or module definition to describe what it does.
They act as documentation for your code, helping others (and yourself) understand the purpose and functionality of that function.
Docstrings are written using triple quotes (""" """) and can be accessed at runtime using the __doc__ attribute.
They are not comments — instead, they are stored as part of the function object, making them a useful way to document code professionally.
Using docstrings improves code readability, maintainability, and clarity.

Example:

def greet(name):
    """This function greets the user by name."""
    print("Hello", name)

print(greet.__doc__)

Output:

This function greets the user by name.

7. Scope and Lifetime of Variables 

The scope of a variable defines where in the program it can be accessed, while the lifetime determines how long it exists in memory.

  • Local Variables:
    These are variables declared inside a function. They can only be accessed within that function and are created when the function starts and destroyed when the function ends.

    Example:

    def func():
        x = 10  # local variable
        print(x)
    func()
    # print(x)  # Error: x not defined outside
    
  • Global Variables:
    Variables declared outside all functions are global. They can be accessed from any part of the program, including inside functions (unless shadowed by a local variable of the same name).

    Example:

    x = 50  # global variable
    def func():
        print(x)
    func()
    print(x)
    
  • Modifying Global Variables:
    If you want to change a global variable inside a function, you must use the keyword global.

    Example:

    x = 10
    def update():
        global x
        x = 20
    update()
    print(x)  # Output: 20
    

In summary, scope decides where a variable can be used, and lifetime decides how long it exists in memory.

8. Lambda (Anonymous) Functions 

A lambda function is a small, anonymous (nameless) function defined using the lambda keyword.
It is used when you need a short, simple function for a quick task — usually where defining a full def function would be unnecessary.
The syntax is:

lambda arguments: expression

The expression is automatically returned, so there is no need to use a return statement.
Lambda functions are often used with built-in functions like map(), filter(), and sorted() to perform quick data transformations or conditions in a single line.
They make code concise and improve readability for simple operations.

Example:

square = lambda x: x ** 2
print(square(5))   # Output: 25

add = lambda a, b: a + b
print(add(3, 7))   # Output: 10

 

9. Recursive Functions

Recursion is a fundamental concept in computer science where a function calls itself to solve smaller parts of a larger problem.

It’s like solving a big problem by breaking it down into simpler, smaller subproblems — until you reach a stage that’s simple enough to solve directly.

In Python, recursion is achieved when a function invokes itself either directly or indirectly.

Example: Factorial calculation

def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(5))

Output:

120

10. Function Nesting (Inner Functions)

Function nesting, also known as inner functions, means defining one function inside another function.
In Python, it is completely valid to define a function within the body of another function. The inner function exists only when the outer function is called, and it can only be accessed inside that outer function.

The main purpose of nested (inner) functions is to organize code, encapsulate logic, and restrict the scope of helper functions that are not needed globally.
An inner function can also access variables from the outer function, which makes it useful for situations where you want to create helper logic that uses outer function data but should not be visible outside.

This concept is widely used in closures and decorators, where inner functions are returned or used to extend functionality dynamically.

def outer():
    def inner():
        print("Inner function called")
    inner()

outer()

Output:

Inner function called

11. Function as Object

Functions in Python are first-class objects, meaning they can be:

  • Assigned to variables
  • Passed as arguments
  • Returned from other functions

Example:

def greet(name):
    return "Hello " + name

say_hello = greet
print(say_hello("Alice"))

Output:

Hello Alice

12. Decorators 

Decorators in Python are a powerful feature that allow you to modify or enhance the behavior of a function without directly changing its code.
They work by wrapping another function inside an additional function, usually called a wrapper, which adds extra functionality before or after the original function runs.

A decorator takes a function as an argument, defines an inner (wrapper) function to perform extra actions, and then returns this wrapper instead of the original function.
By using the @decorator_name syntax above a function definition, Python automatically passes that function to the decorator.

Decorators are commonly used for tasks such as logging, authentication, measuring execution time, access control, and input validation. They help keep code clean, reusable, and organized by separating additional behavior from the core logic of the function.

Example:

def decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()

Output:

Before function call
Hello!
After function call

13. Conclusion

Functions in Python aren’t just reusable code blocks — they are powerful objects that enable:

  • Modular, structured programming
  • Functional and asynchronous design
  • Reusability and abstraction
  • Cleaner and more expressive code

 

Next Blog- Python Built-in Higher-Order Functions

Sanjiv
0

You must logged in to post comments.

Get In Touch

G06, Kristal Olivine Bellandur near Bangalore Central Mall, Bangalore Karnataka, 560103

+91-8076082435

techiefreak87@gmail.com