Types of Functions in Python
Python is a strong and flexible programming language that provides a variety of methods to carry out different activities. Python functions are reusable, ordered chunks of code that are used to carry out particular tasks. There are many types of functions in Python, including built-in functions, user-defined functions, anonymous functions (lambda functions), and higher-order functions, etc.
Built-in Functions
Python comes with a wide range of built-in functions that can be used without importing any additional modules. These functions perform a variety of tasks, such as converting data types, performing mathematical operations, and working with strings, lists, and dictionaries.
Some of the most commonly used built-in functions in Python are:
- print()
- type()
- len()
- int(), float(), str(), list(), dict()
- min(), max()
- sum()
- sorted()
User-defined Functions
User-defined functions are functions that are created by the programmer. These functions can be called and executed just like built-in functions. The “def” keyword is used to declare user-defined functions, which are then followed by the function name and a pair of parentheses. When the function is invoked, the code inside it is indented and run. User-defined functions can take arguments as input and can return values as output.
Here is an illustration of a Python user-defined function:
Example:
def greeting(name):
print ("Hello", name)
greeting("John")
Output:
Hello John
Anonymous Functions (Lambda Functions)
In Python, anonymous functions are called lambda functions. The lambda keyword is used to define these functions, which are then followed by a list of arguments, a colon, and an expression. In contrast to user-defined functions, Lambda functions do not have names and are typically used for quick, single-line tasks. When you wish to give a short function as an argument to another function, lambda functions come in place.
Here is a Python lambda function illustration:
Example:
square = lambda x: x**2
print(square(5))
Output:
25
Higher-order Functions
Higher-order functions are functions that take other functions as arguments and return a function as output. These functions can be used to simplify and modularize code. Higher-order functions are useful for implementing complex operations, such as filtering, mapping, and reducing data. Some of the most commonly used higher-order functions in Python are:
- map()
- filter()
- reduce()
Here is an illustration of a Python higher-order function:
Example:
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(20)
print(add_10(20))
Output:
40
Recursive Functions
Recursive functions are functions that call themselves. These functions are used to perform operations that can be divided into smaller, repetitive tasks. Recursive functions are useful for solving problems that have a repetitive or similar structure, such as calculating factorials, generating Fibonacci numbers, and traversing trees.
Here is an example of a recursive function in Python:
Example:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 5
print("The factorial of", num, "is", factorial(num))
Output:
The factorial of 5 is 120
Decorators
Decorators are special type of functions in Python that are used to modify the behaviour of other functions. Decorators are helpful for integrating new features into pre-existing operations like logging, timing, and authentication.Decorators are declared using the @ symbol followed by the decorator name.
Here is an illustration of a Python decorator:
Example:
def star(func):
def inner(*args, **kwargs):
print("*" * 20)
func(*args, **kwargs)
print("*" * 20)
return inner
def percent(func):
def inner(*args, **kwargs):
print("%" * 20)
func(*args, **kwargs)
print("%" * 20)
return inner
@star
@percent
def printer(msg):
print(msg)
printer("Hello, I am there")
Output:
********************
%%%%%%%%%%%%%%%%%%%%
Hello, I am there
%%%%%%%%%%%%%%%%%%%%
********************
Generators
Generators are functions that generate a sequence of values, one at a time. Generators are useful for working with large datasets and can be used to perform operations such as filtering and transforming data. Generators are declared using the yield keyword, which returns a value and suspends execution of the function until it is called again.
Here is an example of a generator in Python:
Example:
def fibonacci_numbers(nums):
x, y = 0, 1
for _ in range(nums):
x, y = y, x+y
yield x
def square(nums):
for num in nums:
yield num**2
print(sum(square(fibonacci_numbers(10))))
Output:
4895
Higher-Order Functions
Higher-order functions are functions that can either accept other functions as arguments or return functions as output. Higher-order functions are useful for creating more abstract and reusable code.
Here is an illustration of a Python higher-order function:
Example:
def Adding(a):
def Addition(b):
return a + b # addition of two numbers
return Addition # Result
a = int(input("Enter First Number: "))
b = int(input("Enter Second Number: "))
AddVariable = Adding(a)
# Using variable as high order function
Result = AddVariable(b)
print("Sum of these Two numbers is: ", Result)
Output:
Enter First Number: 20
Enter Second Number: 25
Sum of these Two numbers is: 45
Map and Filter Functions
The map and filter functions are built-in functions in Python that can be used to apply a function to each element of a sequence, such as a list or a tuple, and return a new sequence. The map function returns a new sequence that is the result of applying the function to each element of the original sequence, while the filter function returns a new sequence that contains only the elements that satisfy a given condition.
Here is an example of using the map and filter functions in Python:
Example:
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Output:
[1, 4, 9, 16, 25]
[2, 4]
In conclusion, functions are fundamental parts of the Python programming language and play a crucial role in creating efficient and effective code. By understanding the different types of functions in Python, you can write more organized and reusable code, and perform a wide range of operations with ease.