How To Define A Function In Python?

A capacity is a reusable square of code that can play out a fundamental errand. The capacity definition in python might be a piece not the same as the sentence structure utilized in dialects like C, C++, or Java. The target of this article is to give the grammar to work definition in python.

Work definition

The capacity definition begins with a def catchphrase followed by the capacity name and the contentions the capacity can take. These contentions are inside brackets and there can be quite a few contentions including zero. At the point when there is more than one contention, they are isolated by a comma. Since python is an inexactly composed language, (meaning we don’t appoint an information type to a variable when affirmation) we should exclude the information types for the contentions. The capacity definition proclamation is ended by a colon. In python, we characterize a capacity as follows:

def function_name(arg1,arg2,arg3,…):


    work rationale goes here.


    return value1, value2, value3,…

work in python

The following is a basic capacity,

def welcome():

    print(“hello world”)

This is a fundamental capacity that prints “hi world” to the control center.

python capacities parts


Assuming we take a gander at the capacity definition intently, we see that there are no wavy sections around the capacity body. In python, the capacity body is distinguished by the space level. Since we don’t utilize wavy sections to demonstrate the capacity body, the space is helpful for the python mediator to realize what piece of the code characterizes the capacity rationale. On the off chance that we don’t have a space of the capacity rationale comparative with the capacity announcement, an IndentationError will be raised and the capacity won’t be deciphered.

def fun(name):

print(“hello” + name)

The above capacity won’t accumulate and will toss an IndentationError.

Bringing values back

A capacity might return a worth in which case it is insinuated to the translator through the bring explanation back. Not at all like C, C++ or Java, various qualities can be returned by a python work. On the off chance that we do exclude a return explanation, the control will be moved consequently to the calling code without returning any worth. A default worth of None will be returned assuming no return proclamation is there. Likewise with different dialects, a capacity can have all things considered one bring explanation back.

def add(a, b):

    return a + b

def hi():

    print(“Hello world”)

res = add(5,7) #res will have a worth of 12.

res = hi() #res will have a worth of None.

Default contentions

We can set default esteems for contentions in the capacity definition. To do as such we utilize the ensuing punctuation. Note that the default contentions should be on the right half of the contention list. That is, a default contention should just come after all the non-default contentions.

def areaOfCircle(radius, pi=3.14):

    return pi * range * sweep

Here the capacity takes a default contention pi which is characterized on the right half of the contention list. Assuming that we characterize the default contention to one side of a non-default contention we get a SyntaxError.

Calling capacities

Since we have characterized capacities, we perceive how we can call them in our code. To call a capacity we utilize the capacity name alongside contentions that were utilized to characterize the capacity. The quantity of contentions ought to precisely match the quantity of contentions present in the capacity definition. Any distinction in the quantity of contentions will raise the TypeError.

def areaOfCircle(radius, pi=3.14):

    return pi * span * sweep

#work call


#note that the default contention isn’t passed a worth.

#prints 78.5 on the screen.

Work Overloading

Software engineers with C++ or Java foundation would have often over-burden capacities. Over-burdening of capacities doesn’t work in Python since, in such a case that we characterize a capacity at least twice by differing the quantity of contentions, the last characterized capacity will supersede the past definitions. Assuming the capacity with the predetermined number of contentions in the capacity call doesn’t exist we get a TypeError. For eg,

def add(a, b):

    return a + b

def add(a, b, c):

    return a + b + c

print(add(1,2)) #throws a TypeError requesting another contention.

print(add(1,2,3)) #prints 6 on the control center.

Passing capacities as contentions

We can pass a capacity itself as a contention to an alternate capacity. Assume we need to apply a particular capacity to a variety of numbers. Rather than characterizing a capacity and calling it utilizing a for circle, we could simply utilize the guide work. The guide work is a strong implicit capacity that takes a capacity and an assortment of components as contentions and applies the information work across the assortment of components and returns the handled components.

def square(i):

    return I * I

res = list(map(square, [1,2,3]))

#res currently contains [1,4,9]. We have gotten the outcomes without circling through the rundown

*args and **kwargs

Talking about contentions there are a few unique kinds of contentions. Experienced developers might have perhaps utilized in C and C++ this contention. Python offers that abilities as well. On the off chance that we don’t have the foggiest idea the number of contentions a capacity will get during runtime we can involve *args to get those contentions in the capacity definition. We can likewise accomplish work over-burdening utilizing *args additionally despite the fact that it isn’t actually work over-burdening as we are not characterizing different capacities with a similar capacity name.

def add(*args):

    aggregate = 0

    for arg in args:

        aggregate += arg

    bring aggregate back

add(1,2,3) #returns 6

add(1,2,3,4) #returns 10

To get named contentions, we can utilize the **kwargs.

def fun(**kwargs):

    for key in kwargs:

        print(key, kwargs[key])



#a 1

#b 2

#c 3

Order line contentions

Any creation level code would utilize an extraordinary sort of contention. These are order line contentions utilized by the fundamental capacity. In python, those contentions will be passed to the __main__ work. We can undoubtedly get them by parsing the sys.argv variable. Since parsing an order line string is a typical assignment we have libraries to do that for us like argparse.

Instructions to characterize ‘mysterious’ capacities

Mysterious capacities are capacities without a name. They are otherwise called lambda capacities. However, pause! Assuming a capacity has no name how might you call it? These are called where they are characterized. They are not utilized later in the code more often than not. These capacities are unique capacities that are involved when we want to pass a capacity itself as a contention. This case most often happens when we need to do information of some kind handling with pandas or some other library. The capacity may be little that it doesn’t merit its very own name. These capacities are characterized with the watchword lambda.

list(map(lambda x: x*x, [1,2,3]))

#prints esteems [1,4,9]

We have processed the squares of the info list without characterizing a capacity. How we are doing the assertion lambda x: x*x is that we are characterizing a mysterious capacity, i.e without a name, and we are quickly calling it. Assume that we need to utilize the lambda work at a later point we can store that in a capacity variable and use it.

square = lambda x: x*x

list(map(square, [1,2,3]))

#prints esteems [1,4,9]

The variable square stores the capacity to square numbers and we are utilizing it sometime in the future when we need to figure the squares of the numbers in a rundown. While characterizing lambda capacities we should remember the accompanying focuses:

There is no bring proclamation back.

The contentions aren’t composed inside brackets.

There is no space.

Various contentions are isolated by a comma

These capacities are characterized in a solitary line.


This succinct article referenced the means to characterize a capacity and clarified the parts of a capacity. The capacity definition in python might appear to be altogether different contrasted with C, C++ or Java without wavy sections, return types and so on However, when we handle the capacity structure, it becomes simpler to compose more muddled capacities.

How To Call A Method In Java?
How To Check Python Version?
How To Code In Python?
How To Comment Out Multiple Lines In Python?
How To Concatenate Strings In Python?
How To Convert Int To String In Java?
How To Define A Function In Python?
How To Download Python?

Latest Updates

Popular Articles

Related Articles

How To Call A Method In Java?

In this article, we will tell you the best way to call a strategy...

How To Check Python Version?

Python is a preferred shows language. Like many other programming languages, there can be...

How To Code In Python?

Dating from 1991, the Python programming language was viewed as a hole filler, a...

How To Comment Out Multiple Lines In Python?

Does Python uphold multi-line remarks the manner in which different dialects do? What are...