Intermediate Functions
Functions are a set of reusable statements that are called upon to execute a specific task. They can accept and return values. Before we delve into functions and their advantages while developing programs, let us understand their usage. Since the beginning of this tutorial, we've been writing our programs as individual statements to achieve the objective. Let us take an example of adding two numbers together and print their sum.
Well, writing such a small program to print the sum only once is fine. However, What if we have to take input numbers from users and print their sum again at different stages in the program? We can write the same code again, but wouldn't that make our task repetitive, open opportunities for bugs to seep through, add to code duplication, cost more disk as well as RAM space, and be harder to maintain? It will be indeed. What if we could write our statements to perform a specific task only once and reuse the same code when required. In Python, functions allow us to do just that. Now, let's learn how to declare a function and understand its anatomy.
In Python, to declare a function use the def keyword. Here is the syntax:
def <function_name>(args): statement 1 statement 2 ... ... ... statement N return value(s)
Now, let us break down each component.
We use the def keyword to inform Python that a function will be declared, followed by the function_name. Remember, while declaring a function name, we must follow the same rules when declaring a variable.
Arguments follow the function name enclosed in round brackets. Arguments are also known as parameters in other programming languages. Although we can use the term arguments or parameters interchangeably; however throughout this tutorial, we will be using the term argument(s) for consistency. Arguments make it possible for the statements to access information from outside the scope of the function. We can define multiple arguments by separating them with a comma(,). Arguments are optional; therefore, if no external information is required, we can omit them.
Below are a few examples.
As illustrated above, the value "James Bond" corresponds to the argument variable "name", 46 corresponds to "age", "M" corresponds to "gender", and 176 to "weight".
Once arguments are defined in the function definition, it becomes mandatory to pass the value.
These statements define the functionality of the program. They are standard Python code but inside of a function. Whenever we execute a function, these statements are executed.
In the above example,
We have learned about declaring and accepting values into a function. However, after executing our statement(s), we might also need to send values back to be used elsewhere. Python allows for sending values back by using the return statement. We can return multiple values as a tuple from a function. Return statements are optional and can be omitted. By default, any function, if not explicitly returning a value, will implicitly return the value of None. Below are a few examples.
Hello, World
None
100
(2, 3)
Code Readability and Reusability are one of the main advantages of using functions to manage code. Writing statements inside a function makes the code more readable, as it becomes easier to understand the methodology precisely.
The pass statement is a placeholder statement used when a statement is required syntactically but does not do anything. It is used when a function or a block of code is declared but not implemented. For example, when defining the function later. The interpreter ignores this as if it does not exists.
Here are a few examples of pass statements:
Default Arguments are arguments whose predefined values are passed to the function by default. Here is an example:
In this example, the argument "name" has been assigned a "James Bond" default value. If any value is not passed to the function while executing it, the value "James Bond" is automatically given by Python.
James Bond
Mr. Kirk
Do not confuse this with defining an argument and not sending any value. As we have informed Python, it will pass the default value specified if no argument is explicitly passed.
There are certain caveats when using default argument(s). Before we discuss it any further, let's go through an example.
SyntaxError: non-default argument follows default argument
Doing so will generate a Syntax Error. But why so? Remember that arguments and values passed correspond to each other. Let's understand that with an example.
However, we have specified a default value for my_name when calling this function; however, not for the age. When calling a function like
Let's go through another example.
James Bond 46
Please copy the above Python code and execute it. As you can observe, this function is accepted. Take some time to contemplate. After you're done, click to reveal the answer.
No non-default argument can appear after a default argument.
Since Python is a high-level language, it allows for a handy feature; keyword arguments. Keyword arguments allow for the passing of values by specifying the name of the argument. Below is an example demonstrating the usage:
His name is James Bond and his age is 46.
As you can observe, we have passed the value to the argument by specifying its name. Another helpful feature is that the order of the argument does not matter when passing values through keyword arguments.
They both are valid statements.
During development, there are situations when the exact number of arguments is hard to determine. For example, let us take the scenario where you might want to calculate the average scores in Physics of the top 10 students.
Doing so is okay for a beginner but makes the code harder to read, understand, opens opportunities for bugs to appear. Now, what if you might want to calculate the sum for top-20 students instead of 10? Would you write it again with 20 arguments? What about 300 students? To handle such uncertain scenarios, Python provides variable arguments, also known as variadic arguments.
To define a variadic argument, precede the name of the argument with an asterisk (*). Below is an example demonstrating the usage.
Now, to calculate the average, we have to know how many values were passed. We can add a second argument to tell our function precisely that, but Python provides a much more eloquent mechanism. To understand that, we must first understand how Python is passing variable arguments.
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
We are passing multiple values defined in a tuple. As you might remember, we can find out the tuple length using the in-built len() method. Therefore, we can use the len() method to determine how many values have been passed. Let's rewrite the calculate_average function.
1.5
22.666666666666668
37.54545454545455
We have been introduced to variable arguments, but Python also provides variable keyword arguments. They allow for a variable number of variables to be passed as keyword arguments that we learned earlier. Variable keyword arguments can are by prefixing double asterisk '**' to the argument name. You can access the variable by indexing its name.
<class 'dict'> James Bond 46
Variables in keyword arguments are passed as Dictionary data types.
In Programming, recursion is a concept where the function calls itself. Here is an example
0
1
2
3
4
Let us go through the example.
We invoke the function "calling_itself" for the first time with the value 0, and it checks whether the value of "i", which now carries the value "0", is more than or equal to 5; if true, it quits. If not, it prints the value of "i" and calls itself, adding 1 to the current value of i.
You should avoid using Recursive functions as they are hard to understand, maintain, open opportunities for bugs to appear, and are memory intensive.
In this chapter, we learned about functions and their importance, declaring a function using the del keyword, the advantages of using a function, the pass statement, returning values from a function to be used externally.
Additionally, we also learned about passing different types of arguments, recursive functions, and their caveats.