Types of Functions in Python

Types of Functions in Python

7 mins read2.2K Views Comment
Vikram
Vikram Singh
Assistant Manager - Content
Updated on Jun 14, 2024 15:05 IST

This article explains different types of Functions in Python.The functions explained are Built-in Functions, User-defined Functions, Recursive Functions, Lambda Function.

2023_04_MicrosoftTeams-image-12.jpg

A function is a block of code in Python that performs a particular task. It may take zero or more inputs and may or may not return one or more outputs. Functions are reusable and can be called from anywhere in the program.

In this article, we will discuss the types of functions in Python and understand how they carry out specific tasks with the help of examples. 

We will be covering the following sections:

Different Types of Functions in Python

In Python, there are various types of functions that you can use to perform different operations. Here are some of the most commonly used types of functions in Python:

·     Built-in Functions: These functions are built into the Python language and can be used without the need for additional code. Some examples of built-in functions are print(), len(), sum(), min(), max(), etc.

·     User-defined Functions: You create these functions to perform a specific task. You can define your functions using the def keyword followed by the function name, parameter(s), and the code block that performs the desired operation.

·     Recursive Functions: These functions call themselves to perform a task repeatedly until a certain condition is met. Recursive functions can be useful in situations where a problem can be broken down into smaller sub-problems.

·     Lambda Functions: These are small anonymous functions that can be defined in a single line of code. Lambda functions are often used for quick, simple operations that don’t require a full function definition.

·     Higher-Order Functions: These are functions that take other functions as arguments and/or return functions as output. Higher-order functions can be used to create more complex operations by combining simpler functions.

Let’s look at each of these types in detail.

Why Learn Python? Reasons and Top Resources to Learn Python
Why Learn Python? Reasons and Top Resources to Learn Python
Python is an object-oriented programming language that is used everywhere from back-end web servers to front-end development and everything in between. Its high-level built-in data structures mixed with data binding...read more
Top 10 Reasons You Must Learn Python in 2024
Top 10 Reasons You Must Learn Python in 2024
Python is a high-level programming language. It is used to develop many applications, from web applications to intelligent bots of WhatsApp. It has gained much popularity across different domains like...read more
Python Projects for Beginners
Python Projects for Beginners
Python is one of the most widely used programming languages ​​globally because of its general-purpose functionality. Python is suitable for programmers of different skill levels, from students to...read more

Check out the best Python Courses online

Built-in Functions in Python

Function Name Description
print() Outputs a message to the console or standard output device.
input() Takes user input from the console or standard input device.
len() Returns the length of an object, such as a string, list, or tuple.
type() Returns the data type of an object.
range() Creates a sequence of numbers between the specified start and end points.
int() Converts an object to an integer data type.
float() Converts an object to a float data type.
str() Converts an object to a string data type.
bool() Converts an object to a boolean data type.
max() Returns the maximum value in a list or sequence.
min() Returns the minimum value in a list or sequence.
sum() Calculates the sum of a list or sequence.
sorted() Sorts a list or sequence in ascending order.
abs() Returns the absolute value of a number.

Python has many built-in functions that are already defined and ready to use. These functions perform common operations that are frequently used in programming. Here are some of the most commonly used built-in functions in Python:

User-defined Functions in Python

User-defined functions are functions that the programmer creates to perform a specific task or set of tasks. Defining a function allows you to reuse code and makes your code more modular and easier to read. 

In Python, you can define a function using the def keyword, followed by the function name and any parameters it requires in parentheses. The code block that makes up the function is indented beneath the def statement. 

Here’s an example of a simple user-defined function in Python:

 
def greet(name):
print(f"Hello, {name}!")
Copy code

In this example, the greet() function takes one parameter, name, to personalize the greeting. When the function is called, it will print out a message to the console that greets the specified name.

To call a user-defined function, type its name followed by any required parameters in parentheses. Here’s an example:

 
greet("Alice")
Copy code

This would output the following message to the screen:

 
Hello, Alice!
Copy code

User-defined functions can be as simple or as complex as you need them to be. They can include any number of statements, control structures, and other functions and can return one or more values if necessary. When writing a function, it’s important to choose a descriptive name that accurately reflects what the function does and to use clear, concise code that’s easy to read and understand.

Recursive Functions in Python

Recursive functions in Python call themselves to perform a task repeatedly until a certain condition is met. Recursive functions can be used to solve problems that can be broken down into smaller sub-problems that can be solved using the same approach.

Here’s an example of a simple recursive function in Python that calculates the factorial of a given number:

 
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
Copy code

In this example, the factorial() function takes an integer n as its parameter and returns the factorial of that number. The function first checks if n equals 1, which is the base case. If n is not equal to 1, the function calls itself with n-1 as the argument and multiplies the result by n. This process continues recursively until the base case is reached.

To call the factorial() function, pass an integer value as its argument. Here’s an example:

 
print(factorial(5))
Copy code

This would output the following result:

120

Recursive functions can be slower and use more memory than iterative solutions, so they may not be the best choice for large problems. Additionally, recursive functions can be more difficult to debug and understand than iterative solutions, so using them judiciously and only when they provide a clear advantage over other approaches is important.

Lambda Function in Python

In Python, a lambda function is a small, anonymous function that can take any number of arguments but only have one expression. Lambda functions are also known as “anonymous functions” because they don’t require a named function to be created.

The syntax for defining a lambda function in Python is as follows:

 
lambda arguments: expression
Copy code

Here’s an example of a simple lambda function that adds two numbers:

 
add = lambda x, y: x + y
Copy code

In this example, the lambda function takes two arguments, x and y, and returns their sum.

To call a lambda function, you can assign it to a variable and call that variable as a regular function:

 
result = add(3, 5)
print(result) # Output: 8
Copy code

Lambda functions are often used in Python for small, one-off tasks where it’s not necessary to define a separate named function. They can also be used in combination with other functions, such as map()filter(), and reduce(), to create concise and expressive code.

Here’s an example of using a lambda function with the map() function to apply a function to each element of a list:

 
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares) # Output: [1, 4, 9, 16, 25]
Copy code

In this example, the lambda function is used to square each element in the numbers list, and the map() function is used to apply the lambda function to each list element. The resulting list of squared values is then printed on the screen.

Higher-order Functions in Python

In Python, a higher-order function is a function that takes one or more functions as arguments and/or returns a function as its result. Higher-order functions are a powerful feature of functional programming, and they can make code more modular, reusable, and expressive.

Here’s an example of a higher-order function in Python that takes a function as an argument:

 
def apply_function(func, arg):
return func(arg)
Copy code

In this example, the apply_function() function takes two arguments: a function func and an argument arg. The function then calls the func function with arg as its argument and returns the result.

To use the apply_function() function, you can pass it any function that takes a single argument, along with the argument you want to apply the function to. Here’s an example:

 
def square(x):
return x**2
result = apply_function(square, 3)
print(result) # Output: 9
Copy code

In this example, the square() function is defined to calculate the square of a number. The apply_function() function is then called with square as its first argument and 3 as its second argument. The apply_function() function calls the square() function with 3 as its argument and returns the result, which is printed on the screen.

Higher-order functions can also return functions as their result, as shown in the following example:

 
def make_adder(n):
def adder(x):
return x + n
return adder
Copy code

In this example, the make_adder() function takes an integer n as its argument and returns a new function adder. The adder function takes a single argument x, and returns the sum of x and n.

To use the make_adder() function, you can call it with an integer value to create a new function that adds that value to any number you pass it:

 
add_3 = make_adder(3)
result = add_3(5)
print(result) # Output: 8
Copy code

In this example, the make_adder() function is called with the value 3 to create a new function add_3. The add_3() function is then called with the value 5 as its argument, which adds 3 to 5 and returns the result 8.

Endnotes

In this article, we discussed a few Python types of functions. By learning how to use these different functions, you can become more efficient in your Python programming and tackle a wide range of tasks.

I hope this article was helpful to you. You can explore related articles here if you wish to learn more about Python and practice Python programming.

Contributed by Prerna Singh

About the Author
author-image
Vikram Singh
Assistant Manager - Content

Vikram has a Postgraduate degree in Applied Mathematics, with a keen interest in Data Science and Machine Learning. He has experience of 2+ years in content creation in Mathematics, Statistics, Data Science, and Mac... Read Full Bio