How to Define a Function in Python?

ganeshml93 Last Updated : 22 Oct, 2024
9 min read

Introduction

In Python, a function is a block of code that’s reusable and designed to perform a specific task. Its definition, unlike in languages such as C, C++, or Java, follows a distinct syntax. The objective of this article is to outline the syntax for defining functions in Python, understanding terms like function in Python, function definition, and user-defined functions. Additionally, we’ll explore concepts such as the return statement, function name, arguments passed, number of arguments, and default argument values. We’ll delve into various aspects of functions in Python, including lambda functions, default parameter values, and anonymous functions. By examining examples and dissecting Python code, we’ll gain a comprehensive understanding of how to define and utilize functions effectively in Python programs.By the end of these article you will get full understanding on python functions.

This article was published as a part of the Data Science Blogathon

Function Definition

The function definition starts with a def keyword followed by the function name and the arguments the function can take. These arguments are within parentheses and there can be any number of arguments including zero. When there is more than one argument, they are separated by a comma. Since Python is a loosely typed language, meaning we don’t assign a data type to a variable when declaration, we shouldn’t include the data types for the arguments. The function definition statement is terminated by a colon. In Python, we define a function as follows, keeping in mind the concepts of user-defined functions, default arguments, positional-only arguments, and keyword-only arguments.

def function_name(arg1,arg2,arg3,...):
    """
    function logic goes here.
    """
    return value1, value2, value3,...

Below is a simple function,

def greet():
    print("hello world")

This is a basic function that prints “hello world” to the console.

Python Functions

Type of function in Python

There are two main types of functions in Python:

  • Built-in functions: These are functions that are already defined in the Python interpreter. They can be used to perform a variety of tasks, such as printing to the console, converting between data types, and working with files. Some examples of built-in functions include print(), int(), and len().
  • User-defined functions: These are functions that you create yourself. They are defined using the def keyword, followed by the function name, parentheses, and a colon. The function body is then indented. User-defined functions can take arguments and return values.
def greet(name):
  """This function greets the user by name."""
  print("Hello,", name)

greet("Bard")

Indentation

If we examine the function definition closely, we notice the absence of curly brackets around the function body, a hallmark of Python’s syntax. Instead, Python relies on indentation levels to delineate the function body. This indentation serves as a crucial guide for the Python interpreter, signaling which part of the code constitutes the function logic. Without proper indentation of the function logic relative to the function declaration, Python raises an IndentationError, preventing the interpreter from interpreting the function correctly.

Additionally, understanding Python’s approach to indentation is vital for handling various aspects of function definitions, such as positional arguments, default arguments, and global variables. Positional arguments are passed to a function based on their position in the argument list, while default arguments provide predefined values if no value is supplied during function invocation. Moreover, local variables are scoped within the function and are accessible only within its body, distinct from global variables, which are accessible throughout the entire codebase. By adhering to Python’s indentation conventions and mastering the nuances of function arguments and variables, developers can ensure the proper interpretation and execution of Python functions.

def fun(name):
print("hello" + name)

The above function will not compile and will throw an IndentationError.

Returning Values

In Python, a function may return a value using the return statement, a crucial aspect of function definition. Unlike languages like C, C++, or Java, Python allows for the return of multiple values from a single function call, enhancing flexibility in function design. If a return statement is omitted, control automatically transfers back to the calling code, with a default value of None returned implicitly. It’s important to note that a Python function can contain at most one return statement, maintaining consistency with other programming languages.

This feature underscores the versatility of Python functions, which can be defined with various parameters such as positional arguments, keyword arguments, and default arguments. When invoking user-defined functions, developers can pass arguments in different ways, including positional arguments, keyword arguments, or a combination of both. Additionally, Python supports defining functions with positional-only arguments or keyword-only arguments, further enriching the options available to developers when designing function interfaces. By understanding these concepts and mastering Python’s approach to function definition and invocation, developers can leverage the full power of Python functions in their code.

def add(a, b):
    return a + b
def hello():
    print("Hello world")
res = add(5,7) #res will be having a value of 12.
print(res)
res = hello() #res will be having a value of None.

Default Arguments

We can set default values for arguments in the function definition. To do so, we use the subsequent syntax. Note that the default arguments must be on the right side of the argument list. That is, a default argument must only come after all the non-default arguments. This ensures that the function is defined in a way that maintains clarity and consistency, avoiding ambiguity in function calls. Additionally, when setting default arguments, it’s essential to consider the mutability of objects, as mutable objects assigned as default arguments can lead to unexpected behavior, particularly in cases where the default argument is modified within the function body. Therefore, when using default arguments, it’s crucial to exercise caution and ensure that the intended behavior of the function is preserved.

def areaOfCircle(radius, pi=3.14):
    return pi * radius * radius

Here the function takes a default argument pi which is defined on the right side of the argument list. If we define the default argument to the left of a non-default argument we get a SyntaxError.

Calling Functions

Now that we have defined functions, we see how we can call them in our code. To call a function we use the function name along with arguments that were used to define the function. The number of arguments should exactly match the number of arguments present in the function definition. Any difference in the number of arguments will raise the TypeError.

def areaOfCircle(radius, pi=3.14):
    return pi * radius * radius
#function call
print(areaOfCircle(5))
#note that the default argument is not passed a value.
#prints 78.5 on the screen.

Function Overloading

Programmers familiar with languages like C++ or Java often rely on function overloading to define multiple functions with the same name but different parameter lists. However, Python does not support function overloading in the same way. In Python, defining a function multiple times with varying numbers of arguments will result in the last defined function overriding the previous definitions. If a function is called with a specified number of arguments that does not match any existing function definition, Python raises a TypeError.

This fundamental difference in function behavior underscores Python’s approach to function definition and invocation, which prioritizes simplicity and flexibility. While function overloading may not be directly supported, Python offers alternative approaches such as default argument values, variable-length argument lists, and lambda functions to achieve similar functionality. By understanding these distinctions, programmers can leverage Python’s rich ecosystem of functions to build expressive and efficient code. For eg,

def add(a, b):
    return a + b
def add(a, b, c):
    return a + b + c
print(add(1,2)) #throws a TypeError asking for one more argument.
print(add(1,2,3)) #prints 6 on the console.

Passing Functions as Arguments

We can pass a function itself as an argument to a different function. Suppose we want to apply a specific function to an array of numbers. Rather than defining a function and calling it using a for loop, we could just use the map function. The map function is a powerful built-in function that takes a function and a collection of elements as arguments and applies the input function across the collection of elements and returns the processed elements.

def square(i):
    return i * i 
res = list(map(square, [1,2,3])) 
#res now contains [1,4,9]. We have gotten the results without even looping through the list

*args and **kwargs

Speaking about arguments there are some special types of arguments. Experienced programmers may have possibly used in C and C++ this argument. Python offers that capabilities too. If we don’t know how many arguments a function will receive during runtime we can use *args to receive those arguments in the function definition. We can also achieve function overloading using *args also although it is not technically function overloading as we are not defining multiple functions with the same function name.

def add(*args):
    sum = 0
    for arg in args:
        sum += arg
    return sum
add(1,2,3) #returns 6
add(1,2,3,4) #returns 10

If we want to receive named arguments, we can use the **kwargs.

def fun(**kwargs):
    for key in kwargs:
        print(key, kwargs[key])
fun(a=1,b=2,c=3)
#prints 
#a 1
#b 2
#c 3

Command-line Arguments

In Python, command-line arguments play a crucial role in production-level code, serving as inputs to the main function. These arguments are passed to the main function, and we can easily access them by parsing the sys.argv variable. Given that parsing command-line strings is a common task, Python provides libraries like argparse to simplify this process. By leveraging these libraries, developers can efficiently handle command-line arguments, enhancing the usability and functionality of their Python scripts and applications. Additionally, Python’s support for variable-length arguments, both positional and keyword, offers flexibility in defining functions to handle various types of inputs, further enriching the command-line argument parsing process.

How to Define Anonymous Functions

Anonymous functions are functions without a name. They are also known as lambda functions. But wait! If a function has no name how will you call it? These are called where they are defined. They are not used later in the code most of the time. These functions are special functions that are used when we need to pass a function itself as an argument. This case most frequently occurs when we want to do some sort of data processing with pandas or any other library. The function might be so small that it doesn’t deserve a name of its own. These functions are defined with the keyword lambda.

list(map(lambda x: x*x, [1,2,3]))
#prints values [1,4,9]

We have computed the squares of the input list without even defining a function. What we are doing with the statement lambda x: x*x is that we are defining an anonymous function, i.e without a name, and we are immediately calling it. Suppose that we want to use the lambda function at a later point we can store that in a function variable and use it.

square = lambda x: x*x
list(map(square, [1,2,3]))
#prints values [1,4,9]

The variable square stores the function to square numbers and we are using it at a later time when we want to compute the squares of the numbers in a list. While defining lambda functions we should keep the following points in mind:

  • There is no return statement.
  • The arguments aren’t written inside parentheses.
  • There is no indentation.
  • Multiple arguments are separated by a comma
  • These functions are defined in a single line.

How to create a function in Python?

Creating functions in Python is a fundamental way to organize your code and make it more reusable. Here’s a breakdown of the steps involved:

  1. Define the function:
    • Use the def keyword followed by the function name and parentheses.
    • Optionally, you can specify parameters within the parentheses, which act as inputs to the function.
    • Add a colon (:) at the end of the line.
  2. Add function body:
    • Indent the lines of code that make up the function’s body. Indentation is crucial in Python as it defines the scope of the code block.
    • The function body contains the statements you want the function to execute.
  3. Return a value (optional):
    • If the function needs to provide an output, use the return statement followed by the value you want to return.
    • A function can optionally omit the return statement, in which case it returns None by default.

Here’s an example of these steps:

def greet(name):
  """This function greets a person by name."""
  print("Hello,", name + "!")

# Call the function
greet("Alice")

Conclusion

Python’s approach to defining functions offers a unique blend of simplicity and flexibility, allowing developers to create reusable blocks of code tailored to specific tasks. Unlike traditional languages like C, C++, or Java, Python’s function syntax prioritizes readability and conciseness, eschewing elements like curly brackets and return types. By leveraging concepts such as default parameters, positional and keyword arguments, and variable-length argument lists, Python functions empower programmers to handle diverse scenarios efficiently.

Whether it’s processing command-line arguments, utilizing anonymous functions for data manipulation, or handling multiple return values, Python provides a rich ecosystem of tools and techniques to streamline function definition and invocation. By mastering these fundamentals and understanding the nuances of Python’s function paradigm, developers can unlock the full potential of Python’s expressive and dynamic programming capabilities.

Frequently Asked Questions

Q1. What is a function in Python?

A. A function in Python is a reusable block of code designed to perform a specific task. It encapsulates a sequence of statements and can be called multiple times throughout a program.

Q2. How do you define a function in Python?

A. To define a function in Python, you use the def keyword followed by the function name and its arguments enclosed in parentheses. The function body, containing the logic, is indented below the function definition.

Q3. What are keyword arguments in Python functions?

A. Keyword arguments are arguments passed to a function with their corresponding parameter names. They allow for more flexibility in function calls as the order of arguments doesn’t matter when using keyword arguments.

Q4. Can Python functions have default values?

A. Yes, Python functions can have default values for their parameters. Default values are assigned to parameters in the function definition, and if no value is provided during the function call, the default value is used.

Q5. What are lambda functions in Python?

A. Lambda functions, also known as anonymous functions, are functions without a name. They are defined using the lambda keyword and are typically used for short, one-line operations.

Responses From Readers

Clear

Congratulations, You Did It!
Well Done on Completing Your Learning Journey. Stay curious and keep exploring!

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details