Managing repetitive code using functions

Managing repetitive code using functions - Python
© Coventry University. CC BY-NC 4.0

In Python, we tend to reuse code for different parts of our program for ease.

If we were to write the same code over and over again each time we would not only be wasting a lot of time, we’d also likely cause errors in our program. For example, if we have to make changes to each instance of repetitive code and miss one as we’re trading through. So how do we reduce the amount of repetitive code we use?

Functions

We can use functions to reduce the amount of times we have to repeat code. A function is a block of code which we can assign a name. It will only execute that code block when we call its name. We can create a function in python using the def keyword. Let’s take a look at an example.

def Hello(): print("Hello DSAI!")

Here we have declared a function called Hello that will print the message ‘Hello DSAI!’ when we call it. If we run the program as it is, nothing will happen since we are not calling the function.

To call the function, we just have to type its name followed by an open and closed parenthesis. Here is what this would look like if we were to run it in Jupyter Notebook.

def Hello(): print ("Hello DSAI!")Hello()Hello DSAI!

The best part is, we can call it as often as we’d like.

def Hello(): print ("Hello DSAI!")Hello()Hello()Hello()Hello()Hello DSAI!Hello DSAI!Hello DSAI!Hello DSAI!

Function arguments

Since functions are separate from our main program, the code ran inside our function cannot access variables that were declared outside of the function. To get around this we can pass through variables through function arguments when we call the function.

For example, here we have a function with two arguments, numberA and numberB. When the function is called it will print the result of the two numbers added together. However, this now means that when we call the function, we will have to pass through data to each argument.

def AddTwoNumbers(numberA, numberB): print(numberA + numberB)

If we leave the arguments empty, it will give us an error telling us that it received nothing for the arguments.

in[4]: def AddTwoNumbers(numberA, numberB): print(numberA + numberB) AddTwoNumbers()------------------------------------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-4-b871dcb46766> in <module> 3 4----> 5 AddTwoNumbers()TypeError: AddTwoNumbers() missing 2 required positional arguments: 'numberA' and 'numberB'

To avoid errors when we call our function, we need to insert the numbers we want to add together into the brackets of the function call. For example, below we have added together 5 and 10.

def AddTwoNumbers(numberA, numberB): print(numberA + numberB)AddTwoNumbers(5, 10)15

Function return values

We can use function return values to send information back from the function, to the main program. Here we have an example where we use a function to get the square of any number that we pass to it.

def SquareNumber(number): return number **2print (SquareNumber(5))A = Squarenumber(8)print A2564

We can also use function return values as a condition for an If statement if the function returns either true or false.

def IsNumberNegative(number): if (number < 0): return True else return Falseif(IsNumberNegative(-10)): print("The number is negative!")The number is negative!

Libraries in Python

But why reinvent the wheel? In most cases in programming, anything you do has probably been done by someone else and has been packed into a library that you can import into your program. This is extremely handy. With just one line of code we can have an entirely new toolset to use that we won’t have to spend hours writing. We will go over libraries more in Week 2, where we’ll use the MatPlotLib library to automatically generate and draw graphs based on the data we feed it.

Time to put this into practice!
In Jupyter Notebook we’ve prepared an exercise looking at creating our own functions.
Complete the exercises contained in the Jupyter notebook, available in the downloads area.
Hint: the answers are hidden at the bottom of the notebook if you get stuck.
© Coventry University. CC BY-NC 4.0