While programming we often perform the same task repeatedly, such as performing the addition of numbers or printing the same statement with different inputs. These are general examples, but for these would you rather write the same code 10 times or just once?
That’s the purpose of functions, they’re pieces of code only defined once for a particular task and come with reusable functionality so that users can call them whenever they want to perform a task. This makes your program understandable and debugging easier.
Sometimes functions require some input and sometimes they may or may not return some value, but all of these vary from function to function and the task assigned to that specific function. In Python, functions are essential parts that may be user-defined or built-in. In this article, we’ll discuss functions in Python, types of functions, how to define them along examples for your better understanding.
Functions in Python
There are four types into which functions in Python are categorized and each one is useful in its own way, here are these categories:
- User-defined Functions: These are the functions that users create for their own task, and their complexity can vary depending on the task assigned to them.
- Built-in Functions: These are already defined in python that helps users to easily perform the task without creating a function. Such functions are print(), min(), max() and more.
- Recursive Functions: Functions that have the ability to call themselves and executing until a result is reached are called recursive functions.
- Lambda Functions: those functions that are not declared with the keyword “def” are termed as anonymous or Lambda Functions.
Let’s understand each of these with examples to help you understand the concept of functions better.
User-Defined Functions
Those functions in Python that users defined on their own to perform specific tasks in their program are User Defined Functions. These functions reduce the complexity of a program as a particular chunk of code is being called and reused to perform specific tasks with different inputs.
Hence, the program becomes understandable and less complex with easier debugging. This is also useful as sometimes developers are working on larger projects, so the complexity of it is divided into various functions and hence such projects become easy to debug later as you just have to go and find the error in a particular function and not the whole code.
Syntax:
define nameOfFunction(arg1, arg2, .., argN): statement[s] ....
Here:
- nameOfFunction: name you define of the function that can be anything.
- arg1 , arg2, argN: number of arguments that can be single, multiple or none.
- Statement[s]: the line of codes are executed and an action is performed after the function is called.
Here in our Linux system, we have created a file on our desktop with the name “python.py” along with the code saved in it and we’ll run that file using the command provided below in which python3.9 is the version of python being used:
python3 script.py
Example:
The simplest example of a user-defined function would be a simple printing statement that prints when the function is called using the constructor “myFunction()”.
1 2 3 4 | def myfunction(): print("Hello, It's a function I defined") myfunction() |
OutputHello, It's a function I defined
Example:
In this example, we defined an additional function that takes two numbers as arguments and adds them, the result is returned whenever the function is called.
1 2 3 4 5 6 7 8 9 10 | # Program for user-defined functions def additionOfNumbers(i,j): sum = i + j return sum num1 = 10 num2 = 4 print("Sum is", additionOfNumbers(num1, num2)) |
Now if we run the file, it’ll display the following output which shows how functions work.
OutputSum is 14
Built-in Functions
There are 68 built-in functions available to be used in Python to make the task easy for developers. These functions are already defined so that the user doesn’t have to define a function for the simplest task. Let’s see a few of these built-in functions in Python.
A. all()
Python Function:
The all()
function in python takes in a single iterable argument that could be a tuple, list or dictionary and returns a boolean value. True is returned when the given iterable elements are true, else false is returned.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # empty iterable i = [] print(all(i)) # all values true i = [1, 6, 5, 9] print(all(i)) # all values false i = [0, False] print(all(i)) # one false value i = [1, 2, 4, 0] print(all(i)) # one true value i = [0, False, 5] print(all(I)) |
OutputTrue True False False False
B. bin()
Python Function:
The bin()
function takes in a single integer parameter and returns the binary value of that particular integer. In case the parameter passed is not an integer, the function has to implement _index_() method to return an integer.
Example:
1 2 3 | i = 10 print('The binary value of 10 is:', bin(I)) |
OutputThe binary value of 10 is: 0b1010
C. bool()
Python Function:
The bool()
functions in Python generally take one parameter value and return a boolean value. If no parameter is passed or False, None, numeric (0.0, 0) type of parameters are passed, False boolean value is returned, otherwise true is returned.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | i = [] print(bool(i)) i = [0] print(bool(i)) i = True print(bool(i)) i = 0 print(bool(i)) i = None print(bool(i)) i = 'hello' print(bool(I)) |
OutputFalse True True False False True
D. len()
Python Function:
The len()
function in Python either takes in a string, list, tuple, or a collection like a dictionary and returns the length of them in integers.
Example:
1 2 3 4 5 6 7 8 9 10 11 | i = [] print(i, 'length is', len(i)) i = [5, 5, 3] print(i, 'length is', len(i)) i = (5, 2, 3) print(i, 'length is', len(i)) i = range(1, 5) print('Length of', i, 'is', len(I)) |
Output[] length is 0 [5, 5, 3] length is 3 (5, 2, 3) length is 3 Length of range(1, 5) is 4
E. reversed() Python Function:
The reversed()
function takes in a single parameter and returns the output as a reversed iterator.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | # for string i = 'Hello' print(list(reversed(i))) # for tuple i = ('H', 'e', 'l', 'l', 'o') print(list(reversed(i))) # for range i = range(4, 6) print(list(reversed(i))) # for list i = [1, 2, 3, 4, 5] print(list(reversed(i))) [python] <pre class="pretty"> <div class="output">Output</div> ['o', 'l', 'l', 'e', 'H'] ['o', 'l', 'l', 'e', 'H'] [5, 4] [5, 4, 3, 2, 1] </pre> <h2 class="heading1">Recursive Functions </h2> Functions that can call themselves repeatedly in a loop to reach a result are known as Recursive functions. Here we’ve given the classic example of recursive function use which is finding the factorial of a number. In this the <code>factorialFunc()</code> is recursively calling itself with positive integer as a parameter, the number is decreased until it reaches 1 which is the base condition. Each recursive function has a base condition that terminates the program or else it’ll keep calling itself recursively. <strong>Example:</strong> [python] def factorialFunc(x): if i == 1: return 1 else: return (i * factorialFunc(i-1)) num = 5 print("Factorial of", num, "is", factorialFunc(num)) |
OutputFactorial of 5 is 120
Lambda Functions
Those anonymous functions where we don’t use the “def” keyword and directory define them are called lambda functions in Python. Instead of “def” these functions use lambda keywords to be defined. These are mostly used when the user needs to work on smaller codes that don’t require various lines of codes or proper functions.
Syntax:
lambda argument: expression
Here, the number of arguments can be multiple but only one expression is evaluated and returned.
Example:
1 2 3 | # Program for lambda functions double = lambda i: i * 5 print(double(10)) |
Output50
Conclusion
Functions are an essential part of every programming language that helps us reduce the complexity of a program by dividing it into various reusable chunks of code. Python has four different types of functions which we discussed in this article. Users can define their own functions or use the built-in ones in Python.
Furthermore, some functions call themselves repeatedly until the result is reached. The article provided the syntax for each type of function along with examples for your better understanding of functions in Python.