Chapter 4. Running Python Functions

Version 1.0 - 30 June 2016

In Chapter 3 - Evaluating Python Functions you learned how to understand functions. You also learned about how to identify good and bad practices. At this point should have all of the tools necessary to write your own functions when given a task. This chapter will help you practice writing complete functions as well as teach you how to run your functions to see the results.

By the end of the chapter you should be able to:

Writing your own function

In Chapter 2 - Defining Python Functions we looked at the naming of a function to calculate the percentage of the month that is remaining. We are now going to complete this function. Before going on, and without looking back at chapter 2, see if you can write the function on your own.

Chapter 1 - What is Programming? stated that you need to identify the inputs, outputs, and processes that you will need to write the function. The first question you may ask is, what percentage do you want, days, weeks, or hours? You will come across many questions such as this when you program. Therefore, you will want to make sure to ask detailed questions from the client when you program. In this case, we want the percentage to be based on the number of days that are remaining in the month. So, one input will be a number of days passed in the month, and the second input will be the number of total days in the month.

The output will be the percentage of days that are remaining in the month. The processes will be 1) the subtraction of the days that have passed from the total days in the month and 2) the division of the remaining days from the total days in the month. You will find this in Function 4.1.

def calculage_percentage_of_month_remaining (current_day_of_month, total_days_in_month):
    remaining_days = total_days_in_monthcurrent_day_of_month
    percentage_remaining = remaining_days / total_days_in_month
    return percentage_remaining
Function 4.1 Calculate the percentage of the month remaining

It will take practice for programming to feel comfortable. Just remember that it just takes simple steps to write the function.

Calling functions

Functions do not exist alone. In fact, a function will not run unless you ‘call’ the function. Calling a function tells it to run. Calling a function allows you to send in values to the inputs instead of using default values. For example, if you want to run the calculate_percentage_of_month_remaining function with today being the 15th and there being 30 days in the month, you would use the Code 4.1.

calculage_percentage_of_month_remaining (15, 30)
Code 4.1 Calling a function example

Code 4.1 will run Function 4.1, but it is not useful to just run this function. The function returns an answer that is useful, and we need to capture that answer in a variable. Storing the result of a function is accomplished just like storing any other value in a variable (see Code 4.2).

percentage_of_month_remaining = calculage_percentage_of_month_remaining (15, 30)
Code 4.2 Storing the result of a function example

Calling a function with a function

As stated in Chapter 1 - What is Programming?, programming is the combination of sub-processes. It is often the case that the sub-processes need their own function. Putting them in their own function allows them to be combined in different ways without having to rewrite them. The example we used in Chapter 2 - Defining Python Functions of converting inches to miles. However, what if we have a program that converts feet into miles and inches into feet as well. We could write three functions where convert_inches_to_miles does its own math, or we could utilize the two functions about converting inches to feet and converting feet to miles as sub-processes. The later is the more efficient choice. Therefore, convert_inches_to_miles should call the other two functions and use their results. Try it to write it yourself before looking at Code 4.3.

def convert_inches_to_feet (inches):
    feet = inches / 12
    return feet

def convert_feet_to_miles (feet):
    miles = feet / 5280
    return miles

def convert_inches_to_miles (inches):
   feet = convert_inches_to_feet(inches)
   miles = convert_feet_to_miles(feet)
   return miles
Code 4.3 Converting inches to miles using other functions

Running a Python script

Python files are called scripts. There is nothing particularly special about scripts. They are just text files. However, the default text editors are usually poorly equipped for writing code. There are two programs that are better for writing code: TextMate for Macs and Notepad++ for Windows. Download one of them before continuing.

Once you have downloaded the program, open it, and copy and paste Code 4.2. As of right now, none of the functions will run because we do not call them. Therefore, at the bottom of the script add a call to convert_inches_to_miles passing in a value of 360. See if you can do it yourself before looking at Code 4.4. Make sure to save the file in a place that you will remember using the filename convert_inches_to_miles.py.

miles = convert_inches_to_miles(360)
Code 4.4 Calling the convert_inches_to_miles

Now you need to download Python itself. Go to Python Downloads and download the latest Python that starts with a 3 (e.g., Download Python 3.5.2). For Windows, if you see a box to Add Python to PATH, make sure it is selected (see Figure 4.1). For more installation help see: Python Usage.

Python Install - Check Add to PATH
Figure 4.1 Selecting Add Python to PATH

Once Python is installed you will be able to run Python scripts from the command line (Command Prompt in Windows and Terminal on Mac). To open the Command Prompt in Windows, press the Windows key and type ‘cmd.’ To open the Terminal on Mac press the command and space keys and type ‘terminal.’ Once the command line application is open, you can run your script by typing the following command replacing path_to_script with the path to your script.

Python path_to_script\convert_inches_to_miles.py

For example, if I saved my script to my documents folder on Windows and my username is Justin, I would use:

Python C:\Users\Justin\Documents\convert_inches_to_miles.py

If I am on a Mac and saved the script to my documents folder and my username is Justin, I would use:

Python /Users/Justin/Documents/convert_inches_to_miles.py

After pressing enter to run your script, you should not really see anything happen except getting the next command line. This is expected as we have not told the program to display anything on the screen. If you see an error, make sure that you copied and pasted the entire Code 4.3 to your script file. You can also double check that your path is correct.

The print() function

Python comes with some functions already built in. The first function you will learn is print(). The purpose of print() is to display text in the command line. Print expects a single input and outputs the input on the next command line. Code 4.5 contains a few examples.

print(40)
print("Hello")
my_age = 30
print(my_age)
Code 4.5 Examples of the print() function

To run our script from Code 4.3 after adding Code 4.4 you can add Code 4.6 to display the resulting miles in the command line. Make sure to save your file after adding the new line of code. Run the command line statement again to rerun your script.

print(miles)
Code 4.6 Printing the miles conversion in the command line

Practice

1. Write a function to calculate the total amount of money if given pennies, nickels, dimes, and quarters.
2. Write a line of code to call the function exchange_dimes_for_nickels with the four dimes as input.
3. Write a function that calculates volume by first using another function to calculate area (length and width) and a third function to calculate volume based on area and height.
4. Write a line of code to display "Goodbye" in the command line.

Answers to practice problems

1.
def calculate_total_from_coins (pennies, nickels, dimes, quarters):
    pennies_total = pennies
    nickels_total = nickels * 5
    dimes_total = dimes * 10
    quarters_total = quarters * 25
    total = pennies_total + nickels_total + dimes_total + quarters_total
    return total
2.
exchange_dimes_for_nickels(4)
3.
def calculate_area (length, width):
    area = length * width
    return area

def calculate_volume_from_area_height (area, height):
    volume = area * height
    return volume

def calculate_volume (length, width, height):
    area = calculate_area(length, width)
    volume = calculate_volume_from_area_height (area, height)
    return volume
4.
print("Goodbye")
Chapter 5. Modules and Built-in Functions →