In this article, we’ll learn what is a python function, how to define a python function and how to call a python function.
There are two types of functions is python :
- Built-in functions – Functions that are already part of python
- User-defined functions – Functions that are defined by users
A python function is defined using the
def keyword. Let’s check the syntax.
def function_name(parameters): statement
def new_func(): print("Hello World!")
In the above example, we created a function new_func() using def keyword and asked it to print “Hello World!” whenever called. Now, if you just run this piece of code, the code will run but will not show you any output. We need to call the function in order to run the code inside that function.
def new_func(): print("Hello World!") new_func()
Now, when we run the above code, you’ll get the below output.
You can understand a function as a block of re-usable code that will only run when it is called. A function also takes multiple parameters/arguments.
def add(a, b): c = a + b print(c) add(3, 2)
Now, when you run the above code, it will give you the sum of 3 and 2 which is and advantage here that you don’t need to run the same command at multiple places and you can use this function.
We need to make sure the no. of arguments passed in the function and the no. of arguments being passed when calling a function. Suppose, you’ve added two arguments when the function was defined and while calling them you are providing three, it will give you below error.
TypeError: add() takes 2 positional arguments but 3 were given
In the above example, we learnt how to print the sum of two numbers but what if we don’t want to print the output but only return it to store in a different variable? To let a function only return a value, we use
def add(a, b): c = a + b return c result = c print(result)