This article will help the reader continue from the previous Python functions blog along with some basic applications in the real world. We will be using Visual Studio Code as our code editor. If you have not installed Visual Studio Code, the instructions are given in the first blog.

Advanced functions in Python – table of contents:

  1. Passing functions to other functions
  2. Using functions inside a function
  3. *Args in Python
  4. “*” operator in Python
  5. **kwargs in Python

Passing functions to other functions

As discussed in the previous blog, functions in Python are treated as objects. So like objects in Python, functions can also be passed as an argument to another function.

For Example:

def mul(x, y):
    return x*y
 
 
def add(mul, y):
    return mul+y
 
 
x = add(mul(9, 10), 10)
print(x)

In the above code block, it can be seen that the mul function is passed as an argument to the add function and it is stored in the x variable which is then printed to verify the answer.

100

Using functions inside a function

In Python, we can define a function inside another function. These functions are called as nested functions. But in this use case, the inside function or nested function cannot be called separately. Both the examples are illustrated in the following code block.

Let’s write our first function.

def mul(x, y):
 
    m = x*y
 
    def square(m):
        return m*m
 
    return square(m)
 
 
x = mul(9, 10)
 
print(x)
Output:
8100

In the above code block the outer function is “mul” which returns the function square which takes an argument “m” which is the multiplication of two arguments given to “mul” function. The code execution first starts with calling “mul” function, then the product of “x” and “y” gets stored in “m” variable. As this function is returning square function, the “square” function is called and the final product which is the square of “m” is returned.

Let’s learn few important things in Python, which will make your coding journey with Python much better.

*Args in Python

These are the arguments which we use as function parameters. Let’s write a usual function using what we learned till now. We will be writing a function that can give us maximum area of a rectangle given 2 rectangle areas as parameters to the function.

def maxarea(a, b):
    if a > b:
        return f'rectangle a has the more area which is {a}'
    else:
        return f'rectangle a has the more area which is {b}'
 
 
x = maxarea(100, 60)
print(x)
 
Output:
rectangle a has the more area which is 100

This function is good for 2 parameters or arguments, but what if we need to compare more than 2 areas. One approach would be passing a list of areas into the function.

def maxarea(lis):
 
    max = 0
    for i in lis:
        if i > max:
            max = i
 
    return f"rectangle which has the more area is {max}"
 
 
x = maxarea([100, 60, 50])
print(x)
Output:
rectangle which has the more area is 100

This approach is good, but we should know the number of parameters or arguments to give beforehand. In real-time code execution this would be a hassle. Hence to make the programmer’s life easy, Python uses *args and **kwargs.

“*” operator in Python

This operator is an unpacking operator which is usually used to pass an unspecified number of parameters or arguments.

Unpacking arguments into tuple using * operator

As we have seen, that “*” operator is used for unpacking values. The example is illustrated below.


x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
 
z = *x, *y
 
print(type(z))
print(z)
Output:
<class 'tuple'>
(1, 2, 3, 4, 5, 6, 7, 8)

As we can see the unpacking operator has unpacked list x and list y into tuple that is z. We can also see that the result is a tuple.

Let’s write the same function using *Args.

def maxarea(*lis):
 
    max = 0
    for i in lis:
        if i > max:
            max = i
 
    return f"rectangle which has the more area is {max}"
 
 
x = maxarea(100, 60, 50, 200)
y = maxarea(100, 60, 50, 200, 9000)
z = maxarea(100, 60, 50, 20, 90)
print(x)
print(y)
print(z)
Output:
rectangle which has the more area is 200
rectangle which has the more area is 9000
rectangle which has the more area is 100

In this code block we can see that now the arguments are dynamic, we can add any number of arguments that will be unpacked in the maxarea function to give us the desired result. Also, we can compare any number of areas in this context.

**kwargs in Python

The kwargs is like args but it accepts positional arguments. It uses ** operator which has some attributes like unpacking multiple positional arguments of any length, can also unpack dictionaries, can also used for combining two dictionaries.

Merging dictionaries

a = {"h": 1, "n": 2}
b = {"m": 5, "l": 10}
 
c = {**a, **b}
 
print(type(c))
print(c)
 


We can see from the above code that we have 2 dictionaries a and b which are merged using ** operator to give another dictionary.
Output:
 
<class 'dict'>
{'h': 1, 'n': 2, 'm': 5, 'l': 10}

When we use * operator instead of ** operator, the code for this case is illustrated below.

a = {"h": 1, "n": 2}
b = {"m": 5, "l": 10}
 
c = {*a, *b}
 
print(type(c))
print(c)
Output:
<class 'set'>
{'n', 'l', 'm', 'h'}

Hence, when the * operator is used on two dictionaries to merge, the out will be a set with only the keys from the dictionary.

The maxarea function using **kwargs is illustrated in the below code block.

def maxarea(**lis):
 
    max = 0
    for i in lis.values():
        if i > max:
            max = i
 
    return f"rectangle which has the more area is {max}"
 
 
x = maxarea(a=1, b=2, c=3)
y = maxarea(a=1, b=2)
z = maxarea(a=1, b=2, c=3, d=9)
print(x)
print(y)
print(z)
Output:
rectangle which has the more area is 3
rectangle which has the more area is 2
rectangle which has the more area is 9

In this blog about advanced functions in Python, we have covered topics like passing functions to other functions, using functions inside a function, *Args in Python, “*” operator in Python, **kwargs in Python, and more. The further topics which include classes will be covered in the next blog post. Homework regarding advanced functions in Python is given below.

advanced_functions_in_Python

Author: Żaneta Siwik

Python Course From Beginner to Advanced in 11 blog posts:

  1. Introduction to Python Course. Part 1 Python Course from Beginner to Advanced in 11 blog posts
  2. Variables and Data Types in Python. Part 2 Python Course from Beginner to Advanced in 11 blog posts
  3. Python tuples, lists, sets and dictionaries. Part 3 Python Course from Beginner to Advanced in 11 blog posts
  4. Python sets and dictionaries. Part 4 Python Course from Beginner to Advanced in 11 blog posts
  5. Conditional statements in Python. Part 5 Python Course from Beginner to Advanced in 11 blog posts
  6. Loops in Python. Part 6 Python Course from Beginner to Advanced in 11 blog posts
  7. Python functions. Part 7 Python Course from Beginner to Advanced in 11 blog posts
  8. Advanced functions in Python. Part 8 Python Course from Beginner to Advanced in 11 blog posts
  9. Python classes and objects. Part 9 Python Course from Beginner to Advanced in 11 blog posts
  10. Files in Python. Part 10 Python Course from Beginner to Advanced in 11 blog posts
  11. Python applications in practice. Part 11 Python Course from Beginner to Advanced in 11 blog posts