What’s up guyz!!!
Today I am going to describe how to define your functions in Python.
- Need To Define Function
- How to do it?
Need To Define Function…
Do you ever had thought that what happened if you have to write code every time for printing a data in Python instead of using just print() function.
It would have too much hustle and for saving that effort and time there are many pre-defined commands in python. But do you know that you can define your functions in Python and can use them as many times as you want in your program?
For starters, let me make it more clear for you that if you are building a Python program in which you have to ask the name of the user and greet him again and again. So for that, you have to write a command for taking input again and again.
But instead of that, you can just define a function containing a command about taking input. Well then now let us see how we can do it.
How to do it?
It is one of the most basic and simplest method in Python that every beginner should know. So for defining a function in Python we use the def function. Let me show you how to use the def function.
Open your Python IDE and write
def is followed by space and then function name that you want to use for your function and then circular brackets () which are followed by a colon :
Now you have to write code that you want your function to execute. For instance, I want to use this function to say hello to the user and then ask for his name.
For doing that press tab button then write your code. When you click enter after giving the colon, automatically the IDE adds four spaces / tab. This indentation is very important in Python. If you don’t have 4 spaces, python will think that this piece of code is not under the function.
def namaste(): print("What's up dude") name=input("Tell me your good name ") print("That's a nice name ", name, ". If you liked our app then please like and comment on our website")
Now for using this function any number of times in the program you have to write the function’s name i.e. namaste().
Let me show you:
def namaste(): print("What's up dude") name=input("Tell me your good name ") print("That's a nice name ", name, ". If you liked our app then please like and comment on our website") namaste()
Use your creativity…
You know that you can define mathematical calculations in Python. After the declaration of function once you will be able to perform addition, subtraction, or any logic you made once in the program as many times you want, isn’t it amazing? Now it’s all upon you that how you gonna do this.
I will teach more amazing stuffs until then let me show you an addition using the function.
def add(a,b): print(a+b) add(455,477)
Hope you enjoyed reading our today’s blog and found it useful.