![]()
Python functions are reusable blocks of code designed to perform specific tasks. They help developers reduce code repetition, improve readability, and organize programs into smaller, manageable components.
In this blog, we will explore Python functions, including their syntax, types, function arguments, docstrings, return statements, and lambda functions, with practical examples.
Whether you are a beginner learning Python or a professional building applications for data science, machine learning, or Generative AI, understanding functions is essential for writing efficient and maintainable code.
Python Functions Overview
A Python function is a reusable block of code designed to perform a specific computational, logical, or operational task. Functions allow developers to execute the same code multiple times without rewriting it, making programs more organized, readable, and maintainable.
Python supports built-in and user-defined functions, including anonymous functions created using the lambda keyword.
Types of Functions in Python
- Built-in Functions: Predefined functions available in Python, such as print(), len(), sum(), and max().
- User-defined Functions: Custom functions created by developers using the def keyword to perform specific tasks.
- Anonymous Functions (Lambda Functions): Small, single-expression functions created using the lambda keyword without requiring a formal function definition.
Functions are widely used in software development, task automation, data processing, machine learning, and Generative AI applications.
Why Are Functions Needed?
Functions help developers organize code, reduce repetition, and simplify complex programming tasks. They are essential for building scalable and maintainable Python applications.
Here are the key benefits of using Python functions:
- Code Reusability: Write code once and reuse it multiple times throughout a program.
- Modularity: Break complex programs into smaller, manageable components.
- Abstraction: Hide implementation details and simplify how code is used.
- Readability: Make programs easier to understand and maintain.
- Testing and Debugging: Test individual functions and identify errors more efficiently.
- Namespace Separation: Each function call has its own local namespace, helping manage variables and avoid naming conflicts.
Functions are particularly useful in data processing, automation, machine learning, and AI applications, where operations often need to be performed repeatedly.
Python Functions: Basic Syntax
In Python, a function is defined using the def keyword, followed by the function name, parentheses, and a colon. The function body contains the statements that execute when the function is called.
Syntax
def function_name(parameters):
"""Optional docstring."""
# Function body
return expression
Components of a Python Function
- def keyword: Marks the beginning of a function definition.
- Function Name: Identifies the function and follows Python naming conventions.
- Parameters: Optional variables defined within parentheses that receive values when the function is called.
- Colon (:): Marks the end of the function header.
- Docstring: An optional documentation string that describes the purpose of the function.
- Function Body: Contains the statements that perform the required task, typically indented using four spaces.
- Return Statement: Optionally returns a value to the caller. If no return value is specified, the function returns None.
Example
def greet(name):
"""Returns a greeting message."""
return f"Hello, {name}!"
print(greet("Python"))
Output:
Hello, Python!
In this example, name is a parameter, while “Python” is the argument passed during the function call.
For more information, refer to the official Python documentation on defining functions.
Check Out: Our blog post on Python Control Statements.
Creating a Python Function
In Python, a function is created using the def keyword, followed by the function name, parentheses, and a colon. The function body must be properly indented.
Example
def my_function():
print("Hello from a function")
In this example, my_function() defines a function that displays a message when called.
Defining a function does not execute its body immediately. The statements inside the function are executed when the function is called.
Calling a Python Function
Once a function is defined, it can be called by using its name followed by parentheses. If the function requires input values, arguments are passed within the parentheses.
Example 1: Calling a Function Without Arguments
def my_function():
print("Hello from a function")
my_function()
Output:
Hello from a function
Example 2: Calling a Function With Arguments
def greet(name):
print(f"Hello, {name}!")
greet("Python")
Output:
Hello, Python!
A function can be called multiple times with different arguments, allowing developers to reuse the same block of code.
Note: A function must be defined and accessible before its call is executed. Otherwise, Python may raise a NameError.
Arguments in Python Functions
Arguments are values passed to a function when it is called. They allow functions to accept different inputs and perform operations based on those values.
Before understanding the different types of arguments, it is important to distinguish between parameters and arguments.
- Parameters: Variables specified in the function definition.
- Arguments: Actual values passed to the function when it is called.
Example
def add_numbers(num1, num2):
return num1 + num2
result = add_numbers(10, 20)
print("Sum =", result)
Output:
Sum = 30
In this example, num1 and num2 are parameters, while 10 and 20 are arguments.
Example: Passing User Input to a Function
def add_numbers(num1, num2):
return num1 + num2
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print("Sum =", add_numbers(num1, num2))
This example demonstrates how user-provided values can be passed to a function to perform calculations.
Note: Avoid using built-in function names such as sum(), list(), and max() as custom function names, as this can override their accessibility within the current scope.
Types of Function Arguments in Python
Python supports different ways of passing arguments to functions, allowing developers to create flexible and reusable code.
1. Positional Arguments
Positional arguments are passed to a function in the same order as the parameters defined in the function.
def student(name, course):
print(name, course)
student("John", "Python")
Output:
John Python
The order of arguments is important when using positional arguments.
2. Default Arguments
A default argument allows a parameter to have a predefined value that is used when the caller does not provide a corresponding argument.
def calculate(x, y=100):
print("x:", x)
print("y:", y)
calculate(20)
Output:
x: 20
y: 100
Note: Avoid using mutable objects, such as lists or dictionaries, as default parameter values unless shared state is intentional.
3. Keyword Arguments
Keyword arguments allow callers to specify parameter names along with their values. This eliminates the need to remember the order of parameters.
def student(firstname, lastname):
print(firstname, lastname)
student(firstname="K21", lastname="Academy")
student(lastname="Academy", firstname="K21")
Output:
K21 Academy
K21 Academy

4. Variable-Length Arguments
Python allows functions to accept a variable number of arguments using *args and **kwargs.
*args (Variable-Length Positional Arguments)
The *args parameter collects additional positional arguments into a tuple.
def display(*args):
for arg in args:
print(arg)
display("Hello", "Welcome", "to", "K21Academy")
Output:
Hello
Welcome
to
K21Academy

**kwargs (Variable-Length Keyword Arguments)
The **kwargs parameter collects additional keyword arguments into a dictionary.
def display(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
display(first="Welcome", mid="to", last="K21Academy")
Output:
first: Welcome
mid: to
last: K21Academy

5. Positional-Only Arguments (Python 3.8+)
The forward slash (/) indicates that parameters appearing before it must be passed as positional arguments.
def add(a, b, /):
return a + b
print(add(10, 20))
Output:
30
Passing these arguments using parameter names raises a TypeError.
6. Keyword-Only Arguments
The asterisk (*) indicates that parameters appearing after it must be passed using keyword arguments.
def greet(*, name):
print(f"Hello, {name}!")
greet(name="John")
Output:
Hello, John!
Comparison of Python Function Arguments
| Argument Type | Description |
|---|---|
| Positional | Values are passed in parameter order. |
| Default | Uses a predefined value when an argument is omitted. |
| Keyword | Values are passed using parameter names. |
| *args | Accepts additional positional arguments. |
| **kwargs | Accepts additional keyword arguments. |
| Positional-Only | Requires arguments to be passed by position. |
| Keyword-Only | Requires arguments to be passed by parameter name. |
For more information, refer to the official Python documentation on function arguments.
Python Functions supports various types of arguments that can be passed at the time of the function call. Let’s discuss each type in detail.
Check Out: Our blog post on Python Data Visualization.
Python Docstrings
A docstring (documentation string) is a string literal used to describe the purpose and functionality of a Python function. It is placed as the first statement inside the function body and is typically enclosed in triple quotes.
Although docstrings are optional, they are considered a good programming practice because they improve code readability, documentation, and maintainability.
Syntax
def function_name():
"""Describe what the function does."""
# Function body
Example
def even_odd(number):
"""Check whether a number is even or odd."""
if number % 2 == 0:
print("Even")
else:
print("Odd")
even_odd(10)
print(even_odd.__doc__)
Output:
Even Check whether a number is even or odd.
Accessing a Function’s Docstring
Python provides two common ways to access a function’s documentation:
- Using the
__doc__attribute:print(even_odd.__doc__) - Using the built-in help() function:
help(even_odd)
Best Practices for Writing Docstrings
- Clearly describe the purpose of the function.
- Document parameters and return values when necessary.
- Mention exceptions that the function may raise, where relevant.
- Keep documentation concise and up to date.
For more information, refer to the official Python Docstring Conventions (PEP 257).
Return Statement
The return statement in Python is used to terminate function execution and return a value to the caller. The returned value can be stored in a variable or used in further calculations.
Syntax
return expression
Example 1: Returning a Single Value
def square_value(num):
"""Return the square of a number."""
return num ** 2
print(square_value(2))
print(square_value(-4))
Output:
4 16
Example 2: Returning Multiple Values
Python functions can return multiple values, which are automatically packed into a tuple.
def calculate(a, b):
return a + b, a - b
addition, subtraction = calculate(20, 10)
print(addition)
print(subtraction)
Output:
30
10
Example 3: Function Without a Return Statement
If a function does not contain an explicit return statement, Python automatically returns None.
def greet():
print("Hello, Python!")
result = greet()
print(result)
Output:
Hello, Python!
None
Difference Between Return and Print in Python
| Return | |
|---|---|
| Returns a value to the caller. | Displays information on the screen or another output stream. |
| Terminates the current function execution. | Does not terminate function execution. |
| Returned values can be reused in calculations. | The print() function itself returns None. |
Use the return statement when a function needs to provide a result for further processing, and use print() when displaying information to the user.
Anonymous Functions (Lambda Functions)
A lambda function in Python is a small, anonymous function defined using the lambda keyword instead of the def keyword.
Lambda functions can accept multiple arguments but contain only a single expression. The result of that expression is returned automatically without requiring a return statement.
Syntax
lambda arguments: expression
Example 1: Regular Function vs Lambda Function
# Regular function
def cube(x):
return x ** 3
# Lambda function
cube_v2 = lambda x: x ** 3
print(cube(7))
print(cube_v2(7))
Output:
343
343
Both functions perform the same operation. However, lambda provides a shorter way to define simple functions. For named, reusable functions, using def is generally preferred.
Example 2: Lambda Function with Multiple Arguments
add = lambda a, b: a + b
print(add(10, 20))
Output:
30
Example 3: Using Lambda with sorted()
students = [("John", 85), ("Alice", 95), ("David", 75)]
result = sorted(students, key=lambda student: student[1])
print(result)
Output:
[('David', 75), ('John', 85), ('Alice', 95)]
In this example, the lambda function helps sort students based on their scores.
Advantages of Lambda Functions
- Provide a concise way to define simple functions.
- Useful with functions such as map(), filter(), and sorted().
- Simplify short data transformation and sorting operations.
- Useful for temporary, single-expression operations.
Limitations of Lambda Functions
- Can contain only one expression.
- Cannot contain statements such as return, while, or try-except.
- Complex lambda expressions can reduce code readability.
When to use lambda: Use lambda functions for short, simple operations and regular functions defined with def for more complex or reusable programming logic.
For more information, refer to the official Python documentation on lambda expressions.
Is Python Pass by Reference or Pass by Value?
Python uses an argument-passing mechanism known as call by sharing (pass by object reference). When an argument is passed to a function, the function parameter refers to the same object as the argument.
However, the behavior depends on whether the object is mutable or immutable and whether the function modifies the object or reassigns the parameter.
Example 1: Immutable Objects
Immutable objects, such as integers, strings, and tuples, cannot be modified after creation.
def modify_number(num):
num = num + 10
value = 20
modify_number(value)
print(value)
Output:
20
The original value remains unchanged because assigning a new value to num does not modify the original integer object.
Example 2: Mutable Objects
Mutable objects, such as lists, dictionaries, and sets, can be modified after creation.
def modify_list(numbers):
numbers.append(40)
values = [10, 20, 30]
modify_list(values)
print(values)
Output:
[10, 20, 30, 40]
The original list changes because both the function parameter and the caller refer to the same list object.
Mutable vs Immutable Objects
| Mutable Objects | Immutable Objects |
|---|---|
| Lists, dictionaries, and sets | Integers, strings, floats, and tuples |
| Can be modified after creation | Cannot be modified after creation |
| In-place modifications can affect the original object | Reassignment does not affect the original object |
Key takeaway: Python passes object references to functions. Modifying a shared mutable object can affect the original object, but reassigning a function parameter does not change the caller’s variable.
For more information, refer to the official Python FAQ on passing arguments.
Nested Functions in Python
A nested function is a function defined inside another function. The function defined within another function is known as an inner function, while the enclosing function is called the outer function.
Nested functions can access variables from their enclosing scope, making them useful for organizing code and encapsulating internal logic.
Example 1: Creating a Nested Function
def outer_function():
message = "Hello from Python!"
def inner_function():
print(message)
inner_function()
outer_function()
Output:
Hello from Python!
In this example, inner_function() accesses the message variable defined inside outer_function().
Example 2: Using a Closure
A closure allows an inner function to retain access to variables from its enclosing function, even after the outer function has finished executing.
def multiplier(n):
def multiply(x):
return x * n
return multiply
double = multiplier(2)
print(double(5))
Output:
10
Benefits of Nested Functions
- Improve code organization and readability.
- Encapsulate internal function logic.
- Provide access to variables in the enclosing scope.
- Support closures and decorators.
- Help create reusable and modular code.
Nested functions are useful in Python applications involving data processing, decorators, and customized operations.
Type Hints in Python Functions
Type hints allow developers to specify the expected data types of function parameters and return values. Introduced in Python 3.5, they help improve code readability, maintainability, and error detection through static analysis tools.
Syntax
def function_name(parameter: data_type) -> return_type:
# Function body
return expression
Example 1: Function with Type Hints
def add_numbers(a: int, b: int) -> int:
return a + b
print(add_numbers(10, 20))
Output:
30
In this example, both parameters are expected to be integers, and the function is expected to return an integer.
Example 2: Type Hints with Lists (Python 3.9+)
def calculate_average(numbers: list[float]) -> float:
return sum(numbers) / len(numbers)
print(calculate_average([10.0, 20.0, 30.0]))
Output:
20.0
Benefits of Type Hints
- Improve code readability and documentation.
- Help detect type-related errors using static analysis tools.
- Improve IDE code completion and development assistance.
- Simplify collaboration and maintenance of large applications.
- Support structured development in AI/ML and Generative AI projects.
Note: Python does not automatically enforce type hints at runtime. Tools such as mypy and Pyright can be used to detect type-related errors before execution.
For more information, refer to the official Python typing documentation.
Conclusion
Python functions are essential for writing reusable, organized, and maintainable code. Understanding function syntax, different types of arguments, return statements, docstrings, and lambda functions helps developers simplify complex programming tasks.
Advanced concepts such as nested functions and type hints further improve code readability, flexibility, and maintainability.
Whether you are learning Python for software development, data science, machine learning, or Generative AI, mastering Python functions is an important step toward building reliable applications.
Practice creating and calling functions with different arguments and real-world examples to strengthen your Python programming skills.
Frequently Asked Questions (FAQs)
Q1. What is a function in Python?
A Python function is a reusable block of code designed to perform a specific task. Functions help reduce code repetition, improve readability, and organize programs into manageable components.
Q2. What are the different types of functions in Python?
Python supports built-in functions and user-defined functions. User-defined functions can be created using the def keyword or as anonymous functions using the lambda keyword.
Q3. What is the difference between parameters and arguments in Python?
Parameters are variables specified in a function definition, while arguments are the actual values passed to the function when it is called.
Q4. What is the difference between *args and **kwargs in Python?
The *args parameter collects additional positional arguments into a tuple, while **kwargs collects additional keyword arguments into a dictionary. Both allow functions to accept a variable number of arguments.
Q5. What happens if a Python function does not have a return statement?
If a Python function does not contain an explicit return statement, it automatically returns None when execution completes.
Q6. What is the difference between a lambda function and a regular function?
A lambda function is defined using the lambda keyword and contains a single expression. A regular function is defined using the def keyword and can contain multiple statements and complex programming logic.
Q7. Is Python pass by reference or pass by value?
Python uses an argument-passing mechanism known as call by sharing or pass by object reference. Modifying a shared mutable object can affect the original object, but reassigning a function parameter does not change the caller's variable.
Q8. What are type hints in Python functions?
Type hints specify the expected data types of function parameters and return values. They improve code readability and help static analysis tools detect type-related errors, but Python does not automatically enforce them at runtime.











