Python | Tutorial 6 | User-Defined Function

Posted on Posted in Software

In the previous tutorial, we covered range, list, its operation and some list functions. In this lecture, we will cover user defined function. So let’s begin.

If you face trouble in understanding, take a look at our video tutorial on YouTube.

When it comes to some big problems, it is advised to create your own function and we call it as user defined function. You can create it using the def statement. As mentioned earlier, press ctrl+N to open a script and start writing. For example, here I have defined a function:

import time

def hello():
  print(‘make sure to subscribe’)
print(‘hit the bell icon’)


Save it. Run it. Then you will see that the 1st print statement was printed and after a delay of 2 secs, the 2nd one is printed. So here, I have defined function hello first before calling it. If you do it the other way, i.e. you call the function first and then define it, will give you NameError. The code block within every function starts with a colon (:) and is indented. The hello function doesn’t have any argument.

In the next example, let’s take an argument.

def BE(word):


As you can see, the argument is defined inside the parenthesis. You can also take 2 arguments, separated by a comma. Take a look at this function.

def FUNK(x,y):


I hope you understood the function. However, function arguments cannot be referenced outside of the function’s definition.

If you want to return a value, then you can also do it. For example:

def MAX(x,y):
if x>=y:

return x
return y
print(“If you are nothing without this suit, then you shouldn’t have it!“)


Then you will see that we are getting 8. But the print statement of Mr. Stark was not executed. Well, this is because once you return a value from a function, it immediately stops being executed. Any code after return will never happen.

After you have defined a function, suppose, X and then assign it to a variable say Y, then you can use Y to call the function X. Before ending, I must also tell you that functions can also be used as an argument. Let’s take a look.

def add(x,y):
return x+y  

def ADD(func,x,y):
return func(func(x,y),func(x,y))  


So within the 2nd function ADD, we are calling the 1st function add and hence it can deduced as add(add(5,15),add(5,15)) which is add(20,20) which will return 40.

So I hope you guys have enjoyed this tutorial. If yes, then leave a thumbs up and don’t forget to Subscribe and share. Hit the bell icon so that you don’t miss a single video from us. Peace.

Spread it!

Leave a Reply