Hi all, from this text I’m going to talk about functions in Python. In python there are two types of functions,
- Built-in functions
- User defined functions
So far from the previous posts we have talked about built-in functions such as ‘print()‘, ‘len()‘. But from this post I’m going to talk about User defined functions in Python. Here I have shown the syntax of a function,
Let’s see with some examples,
- I have created my first function in Python.
- But no output, because we didn’t call the function. By giving it’s name you can call the function to execute.
- You have to define the function before you are going to call it.
- Also we can pass arguments to a function.
- Let’s see how to pass more than one argument.
- Also we can use the ‘return‘ statement to get an output from a function.
- One thing to remember is that the order of arguments matters.
- But there is a solution in Python as well. You can use Keyword Arguments as a solution.
- When we call the function with not matching number of arguments, then it will produce an error.
- Python have a solution for this too. We can use Default Arguments in this scenario. Then it will use the default argument for the missing argument.
- But the argument what you supply has the higher precedence than the default argument.
- There is another special type of argument as Variable Length Arguments. When we want to execute the same function with different number of arguments, then we can use variable arguments as below.
Without extra arguments :
With one extra argument :
It can take any number of extra arguments :
- Also we can create anonymous functions as well. Anonymous functions do not have the ‘def‘ keyword. It have the ‘lambda‘ instead.
That’s all about functions and passing arguments for function in Python. Hope you have cleared everything here. Hope to see you soon with another interesting topic. Thank You!