Practical programming for the normal person: Functions

Practical programming for the normal person: Functions

(Spectral-Design/Shutterstock)


Save Story
Leer en español

Estimated read time: 6-7 minutes

This archived news story is available only for your personal, non-commercial use. Information in the story may be outdated or superseded by additional information. Reading or replaying the story in its archived form does not constitute a republication of the story.

SALT LAKE CITY — [Last week](http://www.ksl.com/?nid=1012&sid=34541301) we learned how to use variables in Python to store values using a name. This week, we are going to learn about functions.

Functions are one of the most valuable tools in any programming language. Like variables, they are storage devices, but instead of values, functions store entire calculations. This allows us to reuse complex pieces of code without having to retype them every time we need to use them.

At the end of this article, we will be able to use a function to calculate mortgage.

How to use functions

Before we start, there is an important thing to know about Python: Python keeps track of code blocks using indentation. A code block is a section of code that is all related and that is somehow separate from the code around it.

A function contains a code block, which is the code that is run when the function is used. That code is separate because it is not run any other time. To tell Python that a block of code is part of a function, that block is indented more than the code around it, and all of the code in the function is indented to the same level.

Spaces and tabs can be used for indentation, but make sure you pick one or the other, and only use the one you chose. The official Python style guide recommends using spaces.

In high school algebra, functions look like this: f(x) = x**2. The first part is the name of the function, in this case f. The second part is the arguments, which are contained in parenthesis. In this case, there is only one argument, which is called x.

Related Story

Multiple arguments can be separated by commas, for example f(x,y) = x * y. The part after the equal sign is the expression. The expression is what the function returns. When the function appears in a calculation, the x in the expression is replaced by the value of the x position in the arguments, and then the expression replaces the function call. For example, if f(x) = x**2, 12 + f(3) = 12 + 3**2.

Python uses a different syntax for defining functions. The function f(x) = x**2 would look like the following in Python:

def f(x): <br></br>&nbsp&nbsp&nbsp&nbspreturn x**2

In the interpreter, when you run the first line of this, you will be presented with a different prompt, "...". This indicates that you are entering code inside the function. Don't forget the indentation (two or four spaces is pretty common). When you are done entering lines in the function, leave a blank line to tell Python you are done with the function. (If you get an error partway through entering the function, you will have to start over with the first line of the function.)

Once you have the function entered and Python is showing the normal prompt, you can use the function. Something important to note is that the x inside the function is isolated. An x outside the function is a different x than the one inside the function. To illustrate this, enter the following program (after adding the function above):

&nbsp&nbsp&nbsp&nbspf(12)<br></br> &nbsp&nbsp&nbsp&nbsp&nbspx = 2 f(x)<br></br> &nbsp&nbsp&nbsp&nbsp&nbspf(5) print<br></br> &nbsp&nbsp&nbsp&nbsp&nbspx

The first line will display 144. The second will set x (outside the function) to 2. The third line will pass x (which is 2) into the function, which will return 4. The fourth line will return 25. The last line will display the value of the x outside the function, which is still 2. Within the function, x is merely a placeholder for whatever value we pass in.

The name only matters within the function, and the function only has access to values passed in as arguments (this is not entirely accurate, but it is close enough). Similarly, variables created inside functions do not exist outside their functions. A variable with the same name may exist, but it is not the same variable.

We now have a function that calculates the square of a number. This is not that useful, since it is trivial to type without the function. We will conclude this week's article with a more useful function.

Mortgage calculator function

We are going to write a mortgage calculator function, which would be a horrible pain to type out multiple times:

def mort(interest, payments, principal):<br></br>     r = interest / 100. / 12<br></br>     c = (r * principal) / (1 - (1 + r)**-payments) <br></br>     return c

This function takes three arguments. The first is the yearly interest rate as a percentage, the second is the total number of monthly payments, and the third is the loan principal.

Since this calculation is so complex, it would be absurd to type it out multiple times while looking for a home to buy. Instead, we can make a function, and then we can call it multiple times with different arguments.


Watch for part four of our Practical Programming series to go online next Thursday.

Maybe your bank quoted you a 4.5 percent interest rate for a 30 year loan and a 3.0 percent interest rate for a 15 year loan. You have narrowed down the options to a $250,000 house and a $150,000 house, and you want to do some comparisons to see how these would work within your budget.

Here are some examples of how you would use this function to calculate your monthly payments (you can skip the # and everything after it on the same line):

&nbsp&nbsp&nbsp&nbspmort(4.5, 30 * 12, 250000) # 1266.71... <br></br>&nbsp&nbsp&nbsp&nbsp&nbspmort(3.0, 15 * 12, 250000) # 1726.45... <br></br>&nbsp&nbsp&nbsp&nbsp&nbspmort(4.5, 30 * 12, 150000) # 760.02... <br></br>&nbsp&nbsp&nbsp&nbsp&nbspmort(3.0, 15 * 12, 150000) # 1035.87...

You can see that the shorter loan term with the lower interest rate increases payments significantly, but you should also be able to see that the total cost will be less in the long run. If you want to determine the difference, you could run the following line of code.

mort(4.5, 30 * 12, 250000) * 30 * 12 - mort(3.0, 15 * 12, 250000) * 15 * 12

This calculates the monthly payment for each, multiplies the monthly payment by the number of payments to get the total cost, and then it finds the difference between the two costs. The result is a savings of $145,255 for taking the shorter term loan (more than half the price of the house).

As with variables, functions will disappear when you close Python. You will have to enter the functions you want to use each time you start the interpreter. Next week, we will look at some useful functions that are built into Python, and we will look at how to store useful functions to avoid having to manually enter them each time you start Python.


Benjamin Williams is currently a computer science major at BYU-I. He has been programming computers for 20 years and playing with electronics for 10. He has many hobbies, including blacksmithing, model rocketry and writing.

Related links

Related stories

Most recent Features stories

STAY IN THE KNOW

Get informative articles and interesting stories delivered to your inbox weekly. Subscribe to the KSL.com Trending 5.
By subscribing, you acknowledge and agree to KSL.com's Terms of Use and Privacy Policy.

KSL Weather Forecast