How to use Functions In Python
Table of contents
What is a Function?
A function is a set of codes that you can use and reuse. The main purpose of a function is that it should be reusable. If you cannot reuse it, it is not a function. Functions help programmers to break down a large set of code into small actions. A function that is written well will be focused on performing one single task. Let's say you want to write a code that will calculate the roots of a quadratic equation, you may want to do it in about three steps. These three steps can be separated into three different functions.
- Calculate the discriminant
- Calculate the roots
- Display the function
A function can be thought of as a container or a wrapper. For better understanding, let us use a vehicle for instance. On the outside, it has a beautiful body with nice finishing. But inside the vehicle, there may be many engines and electrical components which we may not know their function. All we know how to do is to insert the key, ignite the engine, and zoooooom we are off.
Arguments In Functions
Arguments are the values that we input into a function. It may be considered as the fuel that goes into the function. It is normally placed in the parenthesis that follows the name of a function. Example
def calculate_discriminant(a, b, c):
The arguments in the above functions are
a, b, and c
Return Values In Function
Return values are the output that a function gives after processing the input. The keyword
return
with a small letter r is normally used to return a value. When you can assign a function that has a return value to a variable. And you can print the value on the console, especially while you are still testing the program. For example, this function below displays my name. I can assign it to a variable and print it directly.
def my_name():
return "Oluwatosin Joseph Durodola"
my_full_name = my_name()
print("Below is the output for the variable")
print(my_full_name)
print("\n\n")
print("The output for the function is below")
print(my_name())
Output
Below is the output for the variable
Oluwatosin Joseph Durodola
The output for the function is below
Oluwatosin Joseph Durodola
Creating A Function
- A function in python starts with the keyword def.
def
It tells the python interpreter that a function is about to be defined.
- The name of the function then follows.> Please note that the names you use should be simple and descriptive. Examples:
def sum
def multiply
def divide
- The name of the function is followed by a pair of parenthesis ().
def absolute()
- If the function has parameters the parameters will be inside the parenthesis.
def absolute(number):
If the parameters are more than one, they will be separated with a comma like this.
def multiply(first, second)
A colon : follows the parenthesis to show that an indented code follows.
In python, an indented code is a code that has four spaces before it starts.
An indented block of codes. You can now write your codes that belong to the function, giving four spaces. Example:
def multiply(first, second): result = first * second print("The result is ", result)
Sometimes, the function has a return statement. What you want to do with the function will determine whether you need a return statement or not. Example of a code with a return statement.
def multiply(first, second):
result = first * second
return result
Calling A Function
To call a function (sometimes people refer to this as invoking), you will type the name of the function followed by a pair of parenthesis (). If the function has a parameter, you will have to insert the values that will be used as the parameters.
Please note that parameters are sometimes referred to as arguments. Example of how to call a function.
print()
multiply(5, 6)
# or
first = 4
second = 10
multiply(first, second)
Example of creating and using a Function to Solve Quadratic Equation
Let us now look at an example to explain all the complex things we have been saying so far.
The equation above shows the pattern of how a quadratic equation should be. There are three values we need to calculate the roots. The values are a, b, and c.
Below is the formula to calculate a quadratic equation.
Inside the formula, we find a discriminant. The discriminant of a quadratic equation can affect the result that we will get in the roots. The reason we will want to calculate the discriminant is that
- If the discriminant is positive that is have a plus sign (+) in front or does not have any sign, the quadratic equation will have two different values.
- If the discriminant is zero (0), it means that the two roots of the equation are the same.
- But if the discriminant is negative that is have a minus sign(+) in front, it means that the roots of the equation are not real numbers.
A number that is not a Real number are numbers that have long trails of numbers after a decimal point. Eg.
3.1427897238979889283798
This is the formula for the discriminant in orange color.
As we have said earlier on, we would write three functions to solve quadratic equations.
- Calculate the discriminant
- Calculate the roots
- Display The Results
Calculate The Discriminant
def calculate_discriminant(a, b, c):
result = b**2 - 4 * a * c
return result
The function above calculates the discriminant and assigns it to a variable named result. The result is then returned.
Calculate The Roots
def equation_roots(a, b, c):
discriminant = calculate_discriminant(a, b, c)
result = [0,0]
if discriminant > 0:
result[0] = (-b + sqrt(discriminant))/ (2 * a)
result[1] = (-b - sqrt(discriminant))/ (2 * a)
elif discriminant == 0:
result[0] = 0
result[1] = 0
else:
result[0] = - b / (2 * a)
result[1] = - b / (2 * a)
return result
The above function calculates the roots depending on what the discriminant is. The result is then sent out using the return keyword.
Display The Results
def display_root():
a = int(input("Enter the value for a: "))
b = int(input("Enter the value for b: "))
c = int(input("Enter the value for c: "))
if a == 0:
print("Input a correct quadratic equation")
else:
result = equation_roots(a, b, c)
print(result)
We display the result from the function calulate_roots using this function.
Putting The Code Together
def calculate_discriminant(a, b, c):
result = b**2 - 4 * a * c
return result
def equation_roots(a, b, c):
discriminant = calculate_discriminant(a, b, c)
result = [0,0]
if discriminant > 0:
result[0] = (-b + sqrt(discriminant))/ (2 * a)
result[1] = (-b - sqrt(discriminant))/ (2 * a)
elif discriminant == 0:
result[0] = 0
result[1] = 0
else:
result[0] = - b / (2 * a)
result[1] = - b / (2 * a)
return result
def display_root():
a = int(input("Enter the value for a: "))
b = int(input("Enter the value for b: "))
c = int(input("Enter the value for c: "))
if a == 0:
print("Input a correct quadratic equation")
else:
result = equation_roots(a, b, c)
print(result)
display_root()
We have written the code to solve the quadratic equation.
Advantages of Functions
It reduces the duplication of code. If in the course of adding more code to the ones already written we need to use a discriminant, there will be no need to rewrite any more code to calculate the discriminant. All we have to do is to call the discriminant function.
It breaks down the problem into simpler problems. By using separate functions, it allowed us to focus on a single problem that is smaller and helps us to solve it faster and easier.
It makes the code more easily understood. From looking at the code, we easily point at what code is doing what. And if any changes need to be made, the change can be quickly made.
We can reuse the code as many times as we want to use it. Reusing the code will not cost us any extra memory space on the computer. Because we can reuse the code, it saves us time.
It hides complexity. We don't need to know how the function is doing what it is doing. All we need to know is the parameter it needs and the output we can get from it. This makes it easy to learn and develop faster among teams.
Conclusion
We have looked at functions. I hope that you have learned a thing or two. I will advise that you start using them in your code as you learn. Thank you.
Subscribe to my newsletter
Read articles from Oluwatosin Joseph Durodola directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Oluwatosin Joseph Durodola
Oluwatosin Joseph Durodola
I am a developer from Nigeria