Python function declaration

There are certain questions we need to consider when dealing with function. These common question that pops up in your head is mentioned in this article. Following questions are common when you start programming. 

Declaring function with default parameter

When creating a function we can give them default value in the function definition. For example:

def area_of_triangle(base=1, height=1):
    return (base * height) / 2

a0 = area_of_triangle()  # default base=1, height=1
a1 = area_of_triangle(2)  # by default height will be 1
a2 = area_of_triangle(2, 4)  # here base = 2 and height=4

print("a0=", a0)
print("a1=", a1)
print("a2=", a2)

Here if we don’t pass any value we get a default area with base=1 and height=1, but if we pass a value base and height will be replaced by that value.    


a0= 0.5
a1= 1.0
a2= 4.0

Passing n number of keyword or keyword arguments in python

We use *args, and **kwargs to accomplish this function.

In the previous artcile in function, we discussed about giving multiple parameters to function. We normally do like this

def function_name(parameter1, parameter2, parameter3,...):

If we need  N number of parameters we simply assign N numbers of parameter variable while creating function. However, this solution can be improved. We can use *args to pass any number of arguments to a function. 

Note: Before we move forward lets clarify some terminology in here.

Parameter vs argument: Parameter are simply values that we use when we define a function. For example in above function parameter1 , parameter2 , parameter3 , and so on are parameter to this function. Arguments are values we pass to a function when we make a call. For example if we want to call above function then we might do function_name(2, ‘stringvalue’, 55.5,…)   These values 2 , ‘stringvalue’ , 55.5 ,.. are called arguments.  

arguments vs keyword arguments: An argument is simply a value passed to a function when calling the function. In above example 2, ‘stringvalue’, 55.5, etc are argument. A keyword argument is also a value passed to a function when calling it but it has key and a value pair. It has key=value format when calling a function. Lets understand this via an example.

def function_name(parameter1, parameter2, parameter3):
    print("parameter1=", parameter1)
    print("parameter2=", parameter2)
    print("parameter3=", parameter3)

function_name(1, 2, 3)  # passing arguments

function_name(parameter1=1, parameter2=2, parameter3=3)  # passing keyword arguments

Here the first call is using argument and second call is using keyword argument , both call is valid and will result in same output. Now that we understand the basics, lets resolve our queries, for our solution we use *args and **kwargs if we have any args and kwargs are simply name we can use other name(like *argument_value, and **keyword_argument_value,etc) in there value. The main syntax is single * and double **. Next question that arises is how do we access the passed values inside the function using args and kwargs. Its simple the values will be in the  tuple format for *args and dictionary format for **kwargs.Lets understand this via example:     Example 1: Passing any number of arguments

def sum_numbers(*args):
    total = 0
    for item in args:
        total += item
    return total

sum1 = sum_numbers(10, 20)
sum2 = sum_numbers(1, 2, 3, 4, 5, 6, 7)
sum3 = sum_numbers(-1, -2, -5)

print("sum1=", sum1)
print("sum2=", sum2)
print("sum3=", sum3)

As you can see while calling we have passed 2, 7 and 3 arguments and all work fine. 


args= (10, 20)
args= (1, 2, 3, 4, 5, 6, 7)
args= (-1, -2, -5)
sum1= 30
sum2= 28
sum3= -8

Example: Passing n number of arguments

def sum_numbers(**kwargs):
    print("kwargs=", kwargs)
    total = 0
    for item in kwargs.items():
        total += item[1]
    return total

sum1 = sum_numbers(p1=10, p2=20)
sum2 = sum_numbers(p1=1, p2=2, p3=3, p4=4, p5=5, p6=6, p7=7)
sum3 = sum_numbers(parameter1=-1, parameter2=-2, parameter3=-5)

print("sum1=", sum1)
print("sum2=", sum2)
print("sum3=", sum3)


kwargs= {'p1': 10, 'p2': 20}
kwargs= {'p1': 1, 'p2': 2, 'p3': 3, 'p4': 4, 'p5': 5, 'p6': 6, 'p7': 7}
kwargs= {'parameter1': -1, 'parameter2': -2, 'parameter3': -5}
sum1= 30
sum2= 28
sum3= -8

We can also use builtin sum() function to calculate the sum for example sum([1,2,3]) would give 6 as an output. Note we need to pass an iterable in the sum() function like a list or tuple or set. If we have a dictionary then we can convert that dictionary into a list or tuple or set and pass to the sum function.   

Enforcing type checking in python functions 

As we already know python is a dynamically typed language and types are assigned when we assign certain value to it. If we want to enforce type checking like for int, float, string, etc we can use isinstance() method to know it’s type and raise an error.


isinstance(item, classinfo)

Note: the second argument is class info for integer it it int, for string it is str, for list it is list and so on.


This will output either True or False. If the item is of same type as classinfo then it returns True otherwise False.


def add_two_number(integer1, integer2):
    if not isinstance(integer1, int):
        raise ValueError("First argument not an integer value!")
    if not isinstance(integer2, int):
        raise ValueError("Second argument not an integer value!")
    return integer1 + integer2

result = add_two_number(-20, -30)
print("result=", result)


result= -50

If we call this function using integer and a sting value it will raise an error:

# If we pass another value
add_two_number(44, 'string value')


Traceback (most recent call last):
  File "/home/bhojubuntu/Desktop/Folders/PythonCourseCreation/python_code/", line 66, in <module>
    add_two_number(44, 'string value')
  File "/home/bhojubuntu/Desktop/Folders/PythonCourseCreation/python_code/", line 58, in add_two_number
    raise ValueError("Second argument not an integer value!")
ValueError: Second argument not an integer value!

Leave a Reply

Your email address will not be published. Required fields are marked *