How to Define Function in Python

attributable to its straightforward nature. A fundamental component in Python is the def statement, which serves the purpose of defining functions. In the realm of programming languages, the idea of functions is essential, as they facilitate the encapsulation of code into reusable segments.

In basic terms, a function can be defined as a segment of code designed to execute a particular operation. Functions enhance the modularity of applications and improve the likelihood of reusing application code. In addition to Python's built-in functions such as print, len, and range, the language also allows for the creation of user-defined functions using the def statement.

What is the 'def' Keyword?

In Python, functions are established utilizing the keyword 'def'. The syntax for defining a function follows a particular structure, which is:

def keyword Syntax:

It has the following syntax:

Example

def function_name(parameters):

    """docstring"""

    # Function body

    # ...

    return [expression]

In this syntax,

  • def: This is a reserved word in Python used to define a function.
  • function_name : The name of the function. Like variable names, function names should be meaningful and descriptive. Function names can be written in letters with the first letter in the name in lowercase, and other words concatenated by underscores.
  • Parameters : This is the part that defines the function name. Function names should be self-describable and must use the same criteria as the variable name, which is lowercase, separated by underscores.
  • docstring : Optional. It describes the arguments of the given function. These are the boxes that will be given the value when and if this function is called.
  • Function body : This section of the code performs the task of the function. It carries out action whenever the given function is executed.
  • Return : optional. This is the statement that ends the function and can give a user something in return. If a function has been defined like this, that function will give a return value of None to every case without a return statement.
  • Defining a Simple Function using the def Keyword

To begin, let's define a basic function that generates a straightforward greeting as its output:

Example

Example

def greet():

    """This function greets the user."""

    print("Hello, welcome to Python programming!")

# Calling the function

greet()

Output:

Output

Hello, welcome to Python programming!

Explanation:

In this instance, we have defined a function named greet that does not take any parameters. The function's body consists of a single print statement designed to display a greeting message. To execute the function, we merely invoke it by using its name followed by parentheses .

Understanding the Function Parameters and Arguments

Functions can receive parameters, which are values that are transmitted to the function during the execution of the method call. The parameters supplied may influence the behavior of the function, allowing it to operate differently based on the input it receives.

Positional Arguments

Positional arguments represent the most commonly utilized category of arguments. They are passed to the function according to the sequence in which they were originally specified.

Example

Example

def greet(name):

    """This function greets the user by name."""

    print(f"Hello, {name}! Welcome to Python programming.")

# Calling the function with an argument

greet("Alice")

Output:

Output

Hello, Alice! Welcome to Python programming.

Explanation:

In this illustration, the greet function accepts a single parameter, which is a name. When we call the function, we provide the value "Alice," which is then mapped to the name parameter.

Default Arguments

Parameters can be initialized with default values through the use of default arguments, allowing users the flexibility to leave out particular information if they prefer.

Example

Example

def greet(name="Guest"):

    """This function greets the user by name, defaulting to 'Guest'."""

    print(f"Hello, {name}! Welcome to Python programming.")

# Calling the function without an argument

greet()

Output:

Output

Hello, Guest! Welcome to Python programming.

Explanation:

In this scenario, the name parameter is initialized with a default value of "Guest." Consequently, if an argument is not provided when the function is invoked, the specified default value will be allocated to the name variable.

Keyword Arguments

A significant characteristic of Python, keyword arguments empower users to specify both the names and values of arguments, thereby improving the readability of the function invocation and permitting the arguments to be provided in any order.

Example

Example

def greet(name, message):

    """This function greets the user with a custom message."""

    print(f"Hello, {name}! {message}")

# Calling the function with keyword arguments

greet(message="How are you today?", name="Sarah")

Output:

Output

Hello, Alice! How are you today?

Explanation:

In this example, keyword arguments are employed to assign values to the name and message parameters, allowing them to be specified in a manner that deviates from their standard order.

Arbitrary Arguments

To create a function capable of accepting an indefinite number of arguments, you can utilize args for positional arguments and *kwargs for keyword arguments with ease.

Example

Example

def greet(*names):

    """This function greets multiple users."""

    for name in names:

        print(f"Hello, {name}! Welcome to Python programming.")

# Calling the function with multiple arguments

greet("Alice", "Bob", "Charlie")

Output:

Output

Hello, Alice! Welcome to Python programming.

Hello, Bob! Welcome to Python programming.

Hello, Charlie! Welcome to Python programming.

Explanation:

In this case, the greet function is designed to accept an arbitrary number of positional arguments, which are collected into a tuple referred to as names.

Return Values

The invoking program has the capability to obtain values from the function via the return statement. Any value that is returned through this statement can be employed in later computations or can be assigned to a variable for future use.

Example

Example

def add(a, b):

    """This function returns the sum of two numbers."""

    return a + b

# Calling the function and storing the result

result = add(3, 5)

print(f"The sum is {result}")

Output:

Output

The sum is 8

Explanation:

In this scenario, the add function consists of two arguments: a and b, and it yields their total. This resulting value is stored in the result variable, which is subsequently displayed.

Returning Multiple Values

A function can yield multiple values by separating them with commas. These returned values will be provided to the program in the form of a tuple.

Example

Example

def calculate(a, b):

    """This function returns the sum and difference of two numbers."""

    return a + b, a - b

# Calling the function and unpacking the result

sum_result, diff_result = calculate(10, 4)

print(f"Sum: {sum_result}, Difference: {diff_result}")

Output:

Output

Sum: 14, Difference: 6

Explanation:

In this specific instance, the calculate function outputs both the sum and the difference of a pair of integers. The results obtained are subsequently stored in sumresult and diffresult.

Scope and Lifetime of Variables

This concept is often poorly articulated in programming, which can occasionally lead to errors; it refers to the scope or domain within the code where it can be utilized. In Python, any variables declared within a function are considered local to that specific function, meaning external variables cannot access them. The same principle applies to other situations as well. Conversely, variables that are declared outside of any function are categorized as global, allowing them to be accessed anywhere within the program.

Example

Example

x = 10  # Global variable

def my_function():

    y = 5  # Local variable

    print(f"Inside function: x = {x}, y = {y}")

my_function()

print(f"Outside function: x = {x}")

# print(f"Outside function: y = {y}")  # This will raise an error

Output:

Output

Inside function: x = 10, y = 5

Outside function: x = 10

Explanation:

In this particular instance, x serves as a global variable, while y is identified as a local variable that is declared within the context of the function called my_function. Attempting to reference y from outside the function's scope will result in an error.

Lambda Functions

Similar to the way the def keyword is utilized for defining functions, Lambda Functions represent succinct, unnamed functions, indicating that they lack a designated name. These functions are employed to enhance efficiency and simplify brief operations. Their use aids in boosting the readability of the code.

We can use a Lambda function along with:

  • Condition checking
  • List Comprehension
  • if-else
  • Multiple statements
  • Filter function
  • Map function
  • Reduce function
  • Lambda Function Syntax:

The syntax for a Lambda function in Python is as follows:

Example

Lambda arguments: expression

Parameters:

  • Lambda is the keyword that defines a function.
  • Arguments are the input parameters, which are a list separated by commas.
  • Expression is the entity that gets evaluated and returned.

Let’s explore a practical application of a Lambda function by examining some examples:

Python Lambda Function Example

Here is an illustration of how to add 10 to the variable x:

Example

Example

#using a lambda function

n = lambda x : x + 10

#printing the output, and 10 is the value of x

print(n(10))

Output:

Output

#value of n

20

Explanation:

In this illustration, 'x' serves as the input parameter for the lambda function, while x + 10 represents the expression that is being computed. We supplied the value of x and displayed the resultant output.

Recursive Functions

In Python, functions possess the capability to invoke other functions, or even themselves in specific cases, a concept known as recursion. Recursive functions prove to be particularly useful for tackling problems that can be broken down into analogous sub-problems. A widely recognized illustration of a recursive function is the calculation of a factorial number.

Example

Example

def factorial(n):

    """This function calculates the factorial of a number using recursion."""

    if n == 1:

        return 1

    else:

        return n * factorial(n - 1)

# Calling the recursive function

result = factorial(5)

print(f"The factorial of 5 is {result}")

Output:

Output

The factorial of 5 is 120

Explanation:

In this scenario, the factorial function invokes itself recursively with the argument n - 1, continuing this process until it arrives at the base condition where n equals 1. It is essential for recursive functions to have a base case to avoid endless recursion, which could eventually lead to a stack overflow error.

Nested Functions

Nested functions refer to functions that are created inside another function, a capability offered by Python. These inner functions have a scope limited to the outer function they reside in, making them particularly useful when the inner function needs to interact with specific elements of the outer function.

Example

Example

def outer_function(x):

    """This function contains a nested function."""

    def inner_function(y):

        return y * 2

    return inner_function(x)

# Calling the outer function

result = outer_function(10)

print(f"The result is {result}")

Output:

Output

The result is 20

Explanation:

In this scenario, the outerfunction encompasses the innerfunction, which performs a multiplication of the variable x by 2. This newly defined function cannot be utilized within outer_function, thereby guaranteeing that its scope remains restricted.

Decorators

In Python, decorators allow for the enhancement of a function's abilities without the need to alter its original implementation. A decorator is essentially a function that takes another function as its input, resulting in a wrapper function that possesses additional or altered capabilities.

Example

Example

def my_decorator(func):

    """This is a simple decorator."""

    def wrapper():

        print("Something is happening before the function is called.")

        func()

        print("Something is happening after the function is called.")

    return wrapper

@my_decorator

def say_hello():

    print("Hello!")

# Calling the decorated function

say_hello()

Output:

Output

Something is happening before the function is called.

Hello!

Something is happening after the function is called.

Explanation:

In this scenario, the function sayhello is enhanced with the decorator mydecorator through the use of the @ syntax. As a result, the say_hello function will operate such that the operations defined in the decorator are performed both prior to and following the execution of the function itself.

Best Practices for Using Functions

  • Descriptive Names: Create function names that accurately explain the task being performed by the function .
  • Single Responsibility: Each function is meant to accomplish one task. This principle enhances the modifiability of code .
  • Docstrings: Use docstrings to specify details about the function, such as general operations performed, parameters used, and values returned .
  • Avoid Global Variables: Functions should make almost no use of global variables to avoid problems with side effects .
  • Keep Functions Short: Functions should be short and specific. If the function contains too much information, consider making it into several smaller functions.
  • Understanding the Use of the def Keyword in Classes

In Python, the keyword def has several applications. Beyond its primary function of declaring functions, the def keyword is also employed to create methods within a class. A method is essentially a function that is linked to an object and is invoked using an instance of that class.

By utilizing the def keyword within a class, we can establish methods that have the capability to access and alter the attributes of the class as well as those of its instances.

Python Def Keyword Example in Classes

Let us examine the subsequent example that demonstrates this concept:

Example

Example

# defining the Student class

class Student:

    # defining a constructor to initialize the Student's name, class, and roll number

    def __init__(self, name, class_, roll):

        self.name = name  # Setting the name attribute

        self.class_ = class_    # Setting the class_ attribute

        self.roll = roll    # Setting the roll attribute

    # defining a method to print a greeting message

    def greet(self):

        print(f"Name - {self.name}, Class - {self.class_} and Roll Number - {self.roll}.")

# Creating an instance of the Student class

student1 = Student("Denis", "XI", "6")

# Calling the greet method to display the greeting message

student1.greet()

Output:

Output

Name - Denis, Class - XI and Roll Number - 6.

Explanation:

In this illustration, we have established a class named Student. Inside this class, the constructor has been defined using the def keyword to set up various attributes associated with the class. Following this, we have utilized the def keyword again to create the greet method, which is responsible for outputting a greeting message. Subsequently, we instantiated the Student class and invoked the greet method to present the greeting message for the created object.

Difference Between lambda and def Keyword

In Python, there are a number of distinctions between the lambda and def keywords. The primary differences include the following:

Lambda function def function
It consists of a single expression with a lambda It consists of multiple lines of code.
It is Anonymous, which means without a name It must have a name
It has only a single expression statement. It can consist of many statements.
It is best for temporary and short functions. It is good for complex and reusable logic in the code.

Conclusion

We explored the def keyword extensively. This reserved keyword in Python is utilized for defining functions. Our examination of functions revealed that they can take parameters, which are values provided to the function during its invocation. There are two categories of arguments: args, which permits the inclusion of a variable number of positional arguments, and *kwargs, which facilitates the passing of a variable number of keyword arguments. Additionally, we delved into Lambda functions and discussed the distinctions between them and the def function.

def Function in Python FAQs

1. What is a function in Python?

In Python, a function can be defined as a segment of code designed to execute a particular operation. Functions enhance the modularity of applications and also improve the likelihood of code reuse within the application.

2. How do you define a function in Python?

In Python, the reserved keyword def serves as a means to establish a function.

Example

def greet():

"""This function greets the user."""

print("Hello, welcome to Python programming!")

3. Can functions take parameters?

Indeed, functions are capable of accepting arguments enclosed in parentheses. To illustrate this, let’s examine a specific example:

Code:

Example

def add(a, b):

    return a + b

print(add(5, 3))

Output:

4. What is the difference between parameters and arguments?

  • Parameters: Parameters are the variables that we put inside the function.
  • Arguments: Arguments are the actual values that we give when we call a function.
  • 5. What are *args and **kwargs?

*args: This special keyword enables the transmission of an unspecified number of positional arguments.

**kwargs: This keyword facilitates the passing of a flexible number of keyword arguments.

6. What is the difference between return and print in a function?

  • return: The return function gives back a value to the caller.
  • print: The print function only displays output; it doesn't store or return it.
  • 7. What is a lambda function?

Lambda Functions are brief, unnamed functions that serve to streamline and simplify minor tasks, thereby enhancing the overall clarity of the code.

Syntax:

Example

lambda arguments : expression

Input Required

This code uses input(). Please provide values below: