So far we have seen using python created function for various purpose such as to know the length of list, sort list elements, print information etc.
Can we create our own function?
Yes. We can create our function in Python.
//required code to accomplish a task
- User defined function should always begin with the keyword def
- Immediate after def keyword we need to write the function name
- We can use any function name and it should not contain space or special characters.
- Corresponding code of blocks must follow indent (min. one space)
Lets create a function that prints a message
How can we call the above function?
Where ever I want to print the message in my python script, all I have to do is call the function.
Output: Hello Friends.
Why do we need to create a function?
In python programming, we may land in a situation where a code of block is repeatedly required to write to get a desired result.
Lets say, I am working on GST sales tax calculation application and in the python script there are price of 100 products and in the code I need to calculate GST tax added price for all the products. Suppose there is 18% sales tax is on every product.
Then in the python script, I need to write code that will calculate 18% of the product price and then that is into the actual price. So for 100 products I need to write 100 times the same code whose main task is to calculate tax and prepare the sales price(Actual price+sales tax).
All I can do to avoid such time consuming and effort consuming approach, is to create a function which accepts price, and prints sales price.
See in the above, I have create a function which accepts value, calculates and prints the sales price. The desired value which is passed in the parenthesis is known as “Argument”. We can accept more than one argument in a function and we must have to define in the function itself.
In the above example, the function which I have defined takes one argument. And If I supply more than one argument while calling it, then it will throw error. Similarly, if I do not supply any argument then also it will throw error.
Lets take another example.
Create a function that calculates addition value of supplied two values.
Note: In python we can pass list, tuple, string, float or any data type as an argument.