Functions
Dictionary
Functions are reusable pieces of programs.
Functions allow us to give a name to a block of statements, allowing us to run that block using the specified name anywhere in our application and any number of times.
What does it exactly mean?
Remember we have been using print()
statements. It always performed a predefined task. Well, it turns out it was a function all along.
Example
Alternative print statements,
1 2 3 4 5 6 |
|
Result
1 2 3 |
|
I would suggest you use line number 6 format.
Why use Functions?
Think of a function as a box that performs some operations. We give that box input and in return, it gives back an output after performing some set of operations.
Now, what we have is a box and that box can be used with different inputs, we don't have to write the same set of instructions for every other input value. This made our code simple and to the point.
Primary benefits are:
- Reusability : A function can be used again and again.
- Simplicity : Functions are easy to use and make code readable. We only need to know the purpose of a function and when to use it without focusing on inner working.
Info
The input to a function is OPTIONAL. You can just call a function without any input to perform a set of instructions.
Let's go through an example
Suppose the task in our hand is to find the smallest number between 2 integers.
First, let's go with the code where you don't know about functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Result
1 |
|
As we see, for every defined integer, we need to write the if statement again.
Now, let's do this with help of a function. We will use in-built function min()
.
1 2 3 4 5 6 |
|
Result
1 |
|
Now the code looks cleaner and it is easier to write.
Types of Functions
There are two basic types of functions
- Built-in functions
- User-defined functions
We have used built-in function such as len()
, min()
, and print()
. We can also create our own functions that perform the tasks we require.
Creating Functions
A Function can be defined using the def
keyword in the following format:
1 2 3 4 |
|
- The function name is what we use to identify the function.
- The parameters of a function are the inputs for that function. These inputs can be used within the functions. Parameters are optional.
- The body contains the set of operations.
Our first function.
1 2 3 4 |
|
Result
1 |
|
Functions Parameters
Dictionary
Parameters are the means of passing data to a function that can be used by the function to perform some meaningful task.
When creating a function, we must define the number of parameters and their names. These names are only relevant to that function block and won’t affect variable names elsewhere in the code.
Info
The names given inside the parenthesis of a function definition are called parameters, whereas the values you supply to the function are called arguments.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Result
1 2 |
|
We are passing value1
and value2
to the function. The positions of parameters are important. In the above case, the value of value1
will be assigned to first_num
and likewise, the value of value2
will be assigned to second_num
.
Return Statement
Dictionary
The return statement is used to return values from a function i.e. break out of the function.
Returning a value from any function is optional. Any remaining lines of the code block after the return statement will not be executed.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Result
1 |
|
You can also return multiple values (in the form of a tuple):
1 2 3 4 5 6 |
|
Result
1 2 |
|
Tip
It is a good practice to define all our functions first and then begin the main code.
Scope of a Function
Dictionary
The scope of a function means the extent to which the data items made inside the function are accessible in code.
In Python, data created inside the function cannot be used from the outside unless it is being returned from the function.
Variables in a function block are isolated from the rest of the program. When the function ends, they are released from memory and cannot be recovered.
1 2 3 4 5 |
|
Result
1 2 3 |
|
Altering Data
When mutable data (eg. list) is passed to a function, we can modify the data inside the function. These modifications on mutable objects will stay in effect outside the function scope as well.
1 2 3 4 5 6 7 8 9 10 11 |
|
Result
1 2 |
|
Example
Now look at this example,
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Result
1 2 3 4 5 6 |
|
In the above example, we did alter the data of the list by calling the function. But at line no. 13, when accessing variable num_list
, the compiler threw an error because num_list
was initialized inside the scope of the function and when the task of that function is completed, the variables initialized inside that scope does not have any affect outside.
In the case of immutable data (eg. numbers, strings etc), the function can modify it, but the data will remain unchanged outside the function’s scope.
1 2 3 4 5 6 7 8 9 |
|
Result
1 2 3 |
|
Argument Values
Default Arguments
For some functions, we may want to make some parameters optional and use default values in case the user does not want to provide values for them.
1 2 3 4 5 |
|
Result
1 2 |
|
The function named say is used to print a string as many times as specified.
If we don't supply a value, then by default, the string is printed just once, as we have assigned times
variable as 1.
In line no 4, we supply only the string and it prints the string once.
In line no 5, we supply a string and an argument 3 stating that we want to print the string message 3 times.
Warning
Parameters which are at the end of the parameter list of a function can be given default argument values.
For example,
def hello(name, children=5)
is valid, but def hello(name="maya", children)
is not valid.
Keyword Arguments
If you have a function with many parameters and you want to specify only some of them, then you can give values for such parameters by naming them - this is called keyword arguments.
1 2 3 4 5 6 |
|
Result
1 2 3 |
|
The function named func
argument values has one parameter without a default argument value, followed by two parameters with default
- At line no 4, func(3, 7), the parameter
a
gets the value 3 , the parameterb
gets the value 7 andc
gets the default value 10. - At line no 5, func(25, c=24), the parameter
a
gets the value 25 due to it's position,b
get default value andc
gets value of 24 due to naming. - At line no 6, func(c=50, a=100), we are specifying value for parameter c before a.
Variable Length Arguments
Sometimes we might want to define a function that can take any number of parameters, i.e. n
number of arguments, this can be achieved by using the *
.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Result
1 2 3 4 5 6 7 |
|
When we declare single starred parameter *param
, then all the positional arguments from that point till the end are collected as a tuple.
Similarly, when we declare a double-starred parameter such as **param
, then all the keyword arguments from that point till the end are collected as a dictionary.
Info
More on tuples and dictionaries in later series.
Built-in Functions
Python has a huge library of built-in functions. Let's look at some simple functions.
Info
Functions that are properties of a particular entity are known as methods. These methods are accessed using .
operator.
A method in python is similar to a function, except that it is associated with object and classes. When we talk about classes and objects we generally use methods instead of functions.
More on this in the OOPs module.
One way to find a substring in a string is by using find()
method which returns the first index at which a substring occurs. If no instance is found it returns -1.
1 2 3 4 |
|
Result
1 2 |
|
Let's check out another method replace
,
1 2 3 4 5 6 |
|
Result
1 2 |
|
Uppercasing and lowercasing a string.
1 2 3 |
|
Result
1 2 3 |
|
Lambda Functions
Dictionary
A lambda is an anonymous function that returns some form of data.
These are defined using the lambda
keyword. The lambda keyword creates an inline function that contains a single expression.
SYNTAX:
Let's return the cube of the number using a lambda expression,
1 2 3 |
|
Result
1 |
|
The parameters in the lambda function are optional. We can define it using,
1 2 3 |
|
Result
1 |
|
We can also define lambda function with more than 1 parameter,
1 2 3 |
|
Result
1 |
|
Lambdas are simpler and a lambda cannot have a multi-line expression. We can use conditional statement with lambda,
1 2 3 |
|
Result
1 |
|
In the next section, we will start with Loops.