DEV Community

Cover image for Python def Function: A Complete Guide with Examples
Rachit Joshi
Rachit Joshi

Posted on

Python def Function: A Complete Guide with Examples

Functions are one of the most important building blocks in Python. They help developers organize code, avoid repetition, and create reusable solutions.

Python provides the def keyword to define a function. Whether you are building a small script or a large application, understanding functions is essential for writing clean and maintainable code.

In this article, we will learn what the def function is, its syntax, how to pass arguments, return values, and use default and keyword arguments with practical examples.

What Is a def Function in Python?

The def keyword is used to define a function in Python. A function is a reusable block of code that performs a specific task.

Instead of writing the same code multiple times, you can define it once and call it whenever needed.

Basic Syntax

def function_name(parameters):
# Function body
statements
Explanation
def: Keyword used to define a function.
function_name: Name of the function.
parameters: Optional inputs passed to the function.
Function body: The block of code executed when the function is called.

How to Define and Call a Function

Let's create a simple function that displays a welcome message.

def welcome():
print("Welcome to Python!")

welcome()

Output:

Welcome to Python!

In this example, welcome() defines the function, and the second welcome() statement calls it.

Function with Parameters

Parameters allow a function to receive input values. This makes functions more flexible and reusable.

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

greet("Rachit")
greet("Aman")

Output:

Hello, Rachit
Hello, Aman

Here, name is a parameter, while "Rachit" and "Aman" are arguments passed to the function.

Function with Multiple Parameters

A function can accept multiple parameters separated by commas.

def add_numbers(a, b):
print("Sum:", a + b)

add_numbers(10, 20)

Output:

Sum: 30

The function receives two values and adds them together.

Returning a Value from a Function

The return statement sends a result back to the place where the function was called.

def multiply(a, b):
return a * b

result = multiply(5, 4)
print("Result:", result)

Output:

Result: 20

Unlike print(), the return statement allows the returned value to be stored in a variable or used in another expression.

Function with Default Arguments

A default argument is a value used when no argument is provided during the function call.

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

greet()
greet("Rachit")

Output:

Hello, Guest
Hello, Rachit

The default value "Guest" is used when the function is called without an argument.

Keyword Arguments

Keyword arguments allow you to pass values using parameter names. This makes function calls easier to understand.

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

student_info(age=22, name="Rachit")

Output:

Name: Rachit
Age: 22

The order of keyword arguments does not need to match the order of parameters.

Function with Arbitrary Arguments

Sometimes, you may not know how many arguments a function will receive. Python provides *args and **kwargs for such situations.

Using *args

The *args syntax allows a function to accept multiple positional arguments.

def total(*numbers):
return sum(numbers)

print(total(10, 20, 30))

Output:

60

Here, numbers stores the arguments as a tuple.

Using **kwargs

The **kwargs syntax allows a function to accept multiple keyword arguments.

def display_info(**details):
for key, value in details.items():
print(key, ":", value)

display_info(name="Rachit", city="Noida")

Output:

name : Rachit
city : Noida

The details variable stores the keyword arguments as a dictionary.

Function with a Docstring

A docstring is a string used to describe what a function does. It is written immediately after the function definition.

def square(number):
"""Return the square of a number."""
return number ** 2

print(square(6))

Output:

36

You can access the docstring using the doc attribute.

print(square.doc)
Nested Functions

Python allows you to define a function inside another function. Such functions are called nested or inner functions.

def outer_function():
def inner_function():
print("This is the inner function.")

inner_function()
Enter fullscreen mode Exit fullscreen mode

outer_function()

Output:

This is the inner function.

The inner function is available within the scope of the outer function.

Recursive Functions

A recursive function is a function that calls itself. Recursion is useful for solving problems that can be divided into smaller versions of the same problem.

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

print(factorial(5))

Output:

120

The function repeatedly calls itself until it reaches the base condition.

Example
def square(x):
return x ** 2

square_lambda = lambda x: x ** 2

print(square(5))
print(square_lambda(5))

Output:

25
25

For larger or reusable logic, a regular def function is generally easier to read and maintain.

Advantages of Using Functions in Python

Functions provide several benefits:

  • Code reusability: Write code once and use it multiple times.
  • Modularity: Divide a large program into smaller, manageable parts.
  • Readability: Give meaningful names to specific tasks.
  • Easy debugging: Test individual functions separately.
  • Reduced repetition: Avoid writing the same code again and again.

Better maintenance: Update logic in one place instead of changing it throughout the program.

Best Practices for Defining Functions

  • Use meaningful and descriptive function names.
  • Keep functions focused on one specific task.
  • Use return when a result needs to be reused.
  • Add docstrings to explain important functions.
  • Avoid unnecessarily long functions.
  • Follow Python naming conventions, such as calculate_total().
  • Use default arguments when they make the function easier to use.

Conclusion

The Python def keyword is used to create reusable functions that make programs more organized, readable, and efficient.

By learning parameters, return values, default arguments, keyword arguments, and recursion, you can write more flexible Python programs.

Functions are a fundamental concept for anyone learning Python, and mastering them provides a strong foundation for advanced programming topics.

If you want to explore more Python tutorials, examples, and programming concepts, visit TPointTech for additional learning resources.

Top comments (0)