Python Functions

Video Tutorial
FREE
Functions Introduction thumbnail
This video belongs to
Python Course for Beginners With Certification: Mastering the Essentials
16 modules
Certificate
Topics Covered

Functions are modular blocks of code designed to perform specific tasks. They enhance code efficiency and clarity by reducing code repetition and enabling code reuse.

Types of Functions in Python

Python primarily categorizes functions into two types:

  1. Built-in Functions: These are predefined functions in Python that are readily available for use. Examples include len(), range(), and abs().
  2. User-defined Functions: As the name suggests, these are the functions defined by the users to perform specific tasks.

For a comparative understanding of functions in different programming languages, you can explore the Types of Functions in C.

Python Function Declaration

In Python, a function is declared using the keyword def, succeeded by the name of the function and enclosed parentheses, which may enclose parameters. The syntax is as follows:

  • Function Name: This is the identifier for the function. It follows the same naming conventions as variables in Python. The function name should be descriptive enough to indicate what the function does.
  • Parameters (Optional): These are variables that accept values passed into the function. Parameters are optional; a function may have none. Inside the function, parameters behave like local variables.
  • Function Body: This block of code performs a specific task. It starts with a colon (:) and is indented. The function body typically contains at least one statement. The return statement can be used to send back a result from the function to the caller. None is returned if no return statement is used.

Creating a Function in Python

Creating a function in Python involves defining its structure and specifying the code it will execute. This process is straightforward and follows Python's emphasis on readability and simplicity.

Example:

Calling a Function in Python

A function in Python is called by using its name followed by parentheses. In case parameters are present, these are included in the parentheses.

Example: To call the Function named hello, type the following:

Output:

Learn more about calling a Python function here.

Python Function with Parameters

Parameters are variables declared within the function definition. They act as placeholders for the values that are passed to the function when it is called. This allows a function to perform its task on different data inputs.

Syntax:

Example:

Output:

Python Function Arguments

When you call a function in Python, the values you pass to it are arguments. These arguments are crucial for a function’s operation, as they allow the passing of different data into the function, enabling it to perform operations on varied inputs.

Example:

Output:

Types of Python Function Arguments

Python supports several types of arguments:

  • Positional Arguments: These are the most common arguments, where the argument's value is based on its position. For example, in func(a, b), a and b are positional arguments.
  • Keyword Arguments: The parameter name identifies these and can be supplied in any order, making your code more readable. For instance, func(a=1, b=2) explicitly states which parameter each argument corresponds to.
  • Default Arguments: A parameter with a default value can be omitted in the function call. The function will then use the default value.
  • Variable-length Arguments: You may need to determine the number of arguments supplied to your function. Python allows you to handle this with variable-length arguments, defined with an asterisk *args and **kwargs.

Example:

Output:

Docstring

In Python, documentation strings, or docstrings, are literal strings used to document a Python module, function, class, or method. They are essential for understanding and maintaining code, as they provide a convenient way of associating documentation with Python code.

Syntax to print docstring is:

Example:

Output:

Passing a List as an Argument

Here’s a simple example of a function that takes a list as an argument:

Output:

Python Function within Functions

In Python, functions can be defined inside other functions. These nested functions help organize code into more manageable pieces, encapsulating functionality or creating closures and decorators.

Example:

Output:

Anonymous Functions in Python

An anonymous in Python is a function that is defined without a name. Unlike functions defined using the def keyword, these are defined using the lambda keyword and are hence called lambda functions. They can have 0 or more arguments but only one return value.

Syntax:

Example:

The above example as a usually defined function could be written as:

Output:

Recursive Functions in Python

Recursion is the process in which a function calls itself. Recursive functions are used mostly for sequence generation and to make the code look clean and elegant.

Example of a function to calculate the sum of n consecutive natural numbers recursively:

Output:

Python Library Functions

Python library functions are predefined functions available in Python libraries. These functions offer many functionalities without manual implementation, enhancing productivity and code efficiency.

Example:

Output:

Return Statement in Python

The return statement exits a function and returns to where it was called. This statement can optionally return a value from the function to the caller. If no expression is specified, None is returned.

Syntax:

Example:

Output:

Pass by Reference and Pass by Value

Pass by Reference

  • Concept: a reference (or pointer) to the actual data is passed in pass-by-reference. Modifications to the parameter within the function affect the passed argument.
  • Python's Approach: Python doesn’t strictly follow this but behaves similarly with mutable objects. When a mutable object is passed, changes to it inside the function are reflected outside the function.

Pass by Value

  • Concept: Pass by value means the actual value is passed. The function works on a copy, and changes within the function do not affect the original data.
  • Python's Approach: With immutable objects (like integers and strings), Python's behaviour is akin to pass-by-value. Changes made to an immutable object in a function do not reflect in the original object.

Example:

Output:

Benefits of Python Functions

Helps in increasing code modularity – Python functions help divide the code into smaller problems and solve them individually, thus making it easier to code.

Minimizes Redundancy – Python functions help you save the effort of rewriting the whole code. All you have to do is call the Function once it is defined.

Maximus Code Reusability – Once defined, the Python Function can be called as many times as needed, thus enhancing code reusability.

Improves Clarity of Code – As the extensive program is divided into sections with the help of functions, it helps increase the readability of code while ensuring easy debugging.

Conclusion

Let's recall functions in Python in a nutshell:

  • Functions are used to reduce repetition and make the code more modular.
  • Python neither uses a pass-by-value nor a pass-by-reference mechanism, but it uses pass-by-object reference.
  • We can pass up to 255 parameters in a function in Python.
  • The scope of a variable in a function can be changed from local to global using the global keyword.
  • Pass statement can be used to write an empty function.