When you are writing a big and complex programs, we will notice that there is a repetition of some of the steps in many different places in our program.
Loops also helps in iterating but when you want to use different values every time loops might not be effective when we want to customize.
To rewrite the same set of steps over and over each time, there is a better way in python called “Functions”. Functions can take parameters where you can customize.
What are Functions:
Function is block of code defined with a name.
Functions contain sequence of steps that can be repeated anytime anywhere.
Why Functions:
· We use functions whenever we need to perform the task multiple times without writing the same code again and thereby increasing efficiency and reducing errors.
· Main benefits of functions are reusability and modularity.
· Functions help us to organize your code.
Types of Functions in Python:
1. Built-in functions
2. User defined functions
Built-in functions : Python interpreter has many built-in functions that are readily available. Some of them are shown below.
float(x) |
Convert x to float |
int(x) |
Convert x to integer |
str(x) |
Convert x to string |
type(x) |
Returns type of x |
len(x) |
Returns the length of x |
max(x) |
Returns the maximum of x |
min(x) |
Returns the minimum of x |
round(x,d) |
Returns x rounded to d |
print(x) |
prints x |
User Defined functions:
As the name says user can define function with keyword ‘def’ and the function name of your choice with set of steps to perform specific task. Lets see how you define and call user defined function.
DEFINING & CALLING A FUNCTION:
Defined using def keyword, followed by the function name and set of parentheses with a colon at the end. It is best practice to give your function a descriptive/concise name that describes the task the function performs.
Syntax:
def function_name():
# perform tasks
#optionally, return a result
Calling Function:
• Use the function name followed by parenthesis.
function_name()
Note: Pay attention to indentation when writing the function. Indentations are the spaces at the start of a code line. If colon is missed at the end of the function, it will not create indentation when you click on enter after defining a function. As you can see in the above example print statement is indented to show it’s part of the function body.
We have seen defining function without parameters. But you can pass data inside the parentheses which are known as ‘parameters’ when you define the function.
Parameter – Is a variable passed inside the parentheses when you define a function.
As you can see, we pass parameters when you define the function. But when you call the function, you need to give values to the parameter to perform the specified task. These are called ‘arguments’. Number of parameters passed while defining the function should match with the number of values given while calling the function else it is going to through ‘type error’ (missing arguments).
Argument – Is the value that is passed into the function when it is called.
Both parameters and arguments can be used for the same purpose i.e information passed into the function but the only difference is parameters are passed while defining and arguments are passed while calling.
There are 4 different types of arguments.
1. Default arguments
2. Keyword arguments
3. Positional arguments
4. Variable length of arguments
a. Arbitrary positional arguments
b. Arbitrary keyword arguments
1. Default arguments
Values provided while defining functions
‘=’ used to assign the value
These are optional
We can choose to call the function without providing a value or overwrite the default argument by providing your own value when calling the function.
2. Keyword arguments:
Usually when calling the function, values passed get assigned to the parameters according to their position.
When values get assigned to the arguments by their keyword(name) when function is called are termed as keyword arguments.
3. Positional arguments:
When calling the function, values passed are assigned to the arguments by their position are termed as positional arguments.
For example say (name, age, gender) are the parameters passed when defining the function. Values passed when calling the function are (“Ram”, 35, ”Male”).
Here “Ram” is assigned to ‘name’,
35 is assigned to ‘age’ and so on..
Changing the positions, values will be assigned to the wrong parameters as shown below.
Default arguments, Positional and Keyword arguments in a picture format.
Variable length of arguments:
· These are also called arbitrary arguments.
· When you are not aware of number of arguments required when you are defining function we use arbitrary arguments.
There are two types of Arbitrary arguments
1. Arbitrary positional arguments
2. Arbitrary keyword arguments.
1. Arbitrary positional arguments :
· To pass the variable length of argument we use unpacking operator * before the parameter in the function definition.
· *args(arguments) specifies non-keyword variable number of arguments.
· Allows you to pass multiple non-keyword arguments.
· All the arguments passed are packed in tuple.
From the above example list of values passed to *addition are stored in tuple.
You can check by using type() function.
2. Arbitrary Keyword arguments:
· For arbitrary non keyword arguments double asterisk(**) is placed before a parameter when you define a function.
· ** kwargs(keyword arguments) can hold keyword variable length of arguments.
· Allows you to pass multiple keyword arguments.
· All the arguments passed are packed into dictionary (key-value pairs).
Just to prove the arguments are packed in dictionary lets check the type of the argument.
Within the function **kwargs can be treated as dictionaries so we could iterate over the keys or values or both key-values. Lets see with an example.
Iteration over values:
Iteration over keys:
Iteration over key-values:
Summary and Conclusion:
Positional arguments are arguments that are passed to a function based on its position in arguments list.
Keyword arguments are the arguments passed to a function by specifying name of the parameter and its corresponding value.
Default arguments are the arguments for which the values are assigned to the function parameter when defining the function.
Variable-length arguments are the arbitrary arguments which means varying amount of arguments. When we are not aware of how many arguments the user is going to pass we use *args (arbitrary positional arguments) **kwargs(arbitrary keyword arguments).
Functions are the building blocks of python programs with many advantages that enhance code quality, reusability and modularity.
Since functions are small chunks of code we can test them individually to check if they work as expected. This eliminates testing the whole program which saves time and improves efficiency.
References :
Comments