Defining Functions In Python
A function, once defined, can be invoked as many times as needed by using its name, without having to rewrite its code.
A function in Python is defined as per the following syntax:
def <function-name>(<parameters>):
""" Function's docstring """
<Expressions/Statements/Instructions>
● Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
● The input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
● The first statement of a function is optional - the documentation string of the function or docstring. The docstring describes the functionality of a function.
● The code block within every function starts with a colon (:) and is indented. All statements within the same code block are at the same indentation level.
● The return statement exits a function, optionally passing back an expression/value to the function caller.
Example:
Let us define a function to add two numbers.
def add(a,b):
return a + b
Output:
The above function returns the sum of two numbers a and b.In the example given above, the sum a +b is returned.
Note: In Python, you need not specify the return type i.e. the data type of returned
value
Calling/Invoking A Function
Once you have defined a function, you can call it from another function, program, or even the Python prompt. To use a function that has been defined earlier, you need to write a function call.
A function call takes the following form:
<function-name> (<value-to-be-passed-as-argument>)
The function definition does not execute the function body. The function gets executed only when it is called or invoked. To call the above function we can write:
add(5,7)In this function call, a = 5 and b = 7.
Arguments And Parameters
As you know that you can pass values to functions. For this, you define variables to receive values in the function definition and you send values via a function call statement. For example, in the add() function, we have variables a and b to receive the values and while calling the function we pass the values 5 and 7. We can define these two types of values:
● Arguments: The values being passed to the function from the function call statement are called arguments. Eg. 5 and 7 are arguments to the add() function.
● Parameters: The values received by the function as inputs are called parameters. Eg. a and b are the parameters of the add() function.