Function In Python
A function is a block of code that performs a particular task. There are some situations when we need to write a particular block of code more than once in our program. This may lead to bugs and irritation for the programmer.
Python provides an approach in which you need to declare and define a group of statements once and that can be called and used whenever required. This saves both time and space.
Types of Functions
- Built-in functions
- User-defined functions
- Built-in Functions
Built-in functions are those functions that are already defined in the library. We have used many predefined functions in Python.
User-defined functions are those functions that are defined by the user at the time of writing the program. Functions are made for code reusability and for saving time and space.
Defining a Function
Keyword def is used to start and declare a function. Def specifies the starting of the function block. def is followed by function- the name followed by parenthesis. Parameters are passed inside the parenthesis. In the end, a colon is marked. Python code requires indentation (space) of code to keep it associated with the declared block. The first statement of the function is optional. Following is the statement to be executed.
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt.
Information can be passed to functions as parameter. Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.
Python supports the following types of formal arguments.
- Required argument
- Keyword argument
- Default argument
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.
Using the Keyword Argument, the argument passed in the function the call is matched with function definition on the basis of the name of the parameter.
Default Argument is the argument that provides the default values to the parameters passed in the function definition, in case value is not provided in the function call default value is used.
In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.
To let a function return a value, use the return statement. The the return statement is used to exit a function and go back to the place from where it was called.