Chapter 5. Modules and Built-in Functions
In Chapter 4, we introduced the built-in function called print(). In this chapter we will introduce four more functions int(), float(), round(), and floor(). We will also introduce modules, which are a way of storing functions.
By the end of the chapter you should be able to:
- state the purpose of modules
- write code that imports a module
- state the purpose of int(), float(), str(), round(), and floor()
- explain a situation when you would use int(), float(), str(), round(), and floor()
- predict the results of a function that uses int(), float(), str(), round(), and floor()
- write a function that uses int(), float(), str(), round(), and floor()
Modules
Very excellent programmers often build functions that can be used by a lot of different people. However, since not everyone needs these functions they are not automatically available when you write your functions. They are however, stored in modules.
A Module is a set of functions that can be imported into a program so that the program has the ability to use the functions. There is already a built-in function in Python to round a number (e.g., 2.3 to 2.0). You can also round to a specified number of decimal places by adding a second input to the function.
round(2.3)
round(2.345,2)
However, there is not a built-in function to floor a number (or round to the largest integer not above a given number). Luckily, someone has already built a function to floor. The floor function is stored in a module called math.
To use the floor function, we need to first import the math module. Then we can call the function by placing the module name and a period in front of the function.
import math
math.floor(2.6)
Types of numbers
We call anything that looks like a number, a number. However, computers have more than one type of number. The most common two are integers and floats. An integer, often shortened to int, is a positive or negative number that does not have a decimal (e.g., -3, -2, -1, 0, 1, 2, 3). A float is a positive or negative number that does have a decimal (e.g., -1.0, -0.9, -0.1, 0.0, 0.1, 0.9, 1.0). Applying arithmetic between a int and a float will result in a float. However, there may be times when you need to explicitly convert one type into another. Fortunately, there are built-in functions to do the conversion for you. The first line below converts the float 4.3 to the integer 4. The second line converts the integer 5 to the float 5.0.
int(4.3)
float(5)
At first appearance, the int() function and the floor function appear to do the same thing. However, int() just strips the decimal off of the number where floor() finds the largest integer not above the given number. This makes a difference on negative numbers where int(-2.9999) becomes -2 and floor(-2.9999) becomes -3.
Converting strings and numbers
When we read a sentence, we call it a sentence or a set of words. When we see a number, such as 4, in a sentence, we still consider it part of a sentence. When a computer sees a sentence, it calls it a string. The computer sees all of the letters and numbers in the string as characters instead of numbers. Everything that you type is considered a string. The computer also likes to surround the characters in quotes so that it knows where the string starts and stops. Here are some example strings. None of them can be added or multiplied.
"This is a string", "Another string with 3", "4.0"
You can also use single quotes around a string. This is especially useful if you want double quotes as part of your string. This is an example of one string with double quotes.
'This is a "string" with double quotes.'
There are situations when you need to switch between strings and numbers. For example, when filling out how much to transfer from you bank account in an online form. What you type in is a string that cannot be added to your balance. What you type first needs to be converted to a number. Luckily, there are built-in functions that can convert between them for you. Two of them you have already seen. Both int() and float() can also take strings as input. The last function, str(), can convert either a int or a float into a string.
int("6.7")
float("-3.6")
str(6)
string(6.8)
Predicting the result of a function
In Chapter 3 you learned to to read a function and predict its results. We will walk you through an example using some of the new functions. This first function adds a deposit to your current balance. The second prints the current balance.
deposit = "100.0"
balance = 345.6
def add_to_balance (deposit, balance):
deposit_number = float(deposit)
new_balance = balance + deposit_number
return new_balance
new_balance = add_to_balance(deposit, balance)
def print_balance (balance):
print("Balance: " + str(balance))
print_balance(new_balance)
The first two lines define the values of two variables, deposit and balance. The second line defines a function that takes two variables called deposit and balance. While these two variables are named the same, they are not same as the previous variables. The function uses new variables. The third line converts the deposit, in this case the string "100.0" into a float 100.0. The fourth line creates a new balance. The fifth line returns the new balance, in this case 445.6. The sixth line, calls the add_to_balance function. Remember that functions do not run until they are called. The seventh line defines a new function to print the balance. The eight line converts balance from a number to a string so that it can be appended to the end of the string "Balance: ". Finally, the ninth line calls the print_balance function.
Writing your own function
Back in Chapter 1, we talked about calculating on average how fast someone runs a mile. We discussed the sub-processes 1) convert miles per hour to minutes per mile, 2) convert the decimal to seconds, and 3) combine the minutes with the seconds. Here is the example that we used.
60 minutes / 7.2 miles = 8.333 minutes per mile
0.333 * 60 seconds = 20 seconds
8 minutes and 20 seconds / mile
We also said that we would need four functions to perform all of the necessary calculations. We will walk through each of the functions that we need to perform this calculation. See Code 5.6.
The first function divides 60 minutes by the number of miles someone runs in an hour to calculate the miles per minute. Instead of just limiting the function to 60 minute increments, we will make the minutes an input as well. Thus, there are two inputs, miles and the number of minutes.
def convert_miles_and_minutes_to_minutes_per_mile (miles, minutes):
return minutes / miles
The second function retrieves just the decimal portion of a number. This way we can get the 0.333 from the 8.333. We can calculate this number by using the floor function on the number (8) and subtracting that from the original number (8.333).
def get_decimal_portion_of_number (number):
return number – math.floor(number)
The third function converts decimals of a minute into seconds. This function only needs one input.
def convert_decimal_minutes_to_seconds (decimal_minutes):
return decimal_minutes * 60
The final function uses the previous three functions and returns a string. This function also needs two inputs: the number of miles and the number of minutes.
def convert_miles_per_hour_to_minutes_per_mile (miles, minutes):
minutes_per_mile = convert_miles_and_minutes_to_minutes_per_mile (miles, minutes)
decimal_minutes = get_decimal_portion_of_number (minutes_per_mile)
seconds = convert_decimal_minutes_to_seconds (decimal_minutes)
miles_per_minute_string = str(floor(minutes_per_mile)) + " minutes and " + str(seconds) + " seconds per mile"
Practice
- Add custom functions to your code.
- Split of learning about code.
- Bundle functions together to use when needed.
- Make your code smaller.
- import ______
- add ______
- add module _______
- include ________
- Converts x to a float
- Converts x to a string
- Rounds x to the nearest integer
- Converts x to an integer
- Rounds x to the largest integer less than or equal to itself
- int()
- float()
- round()
- floor()
- string()
def convert (x = "1"):
return float(x)
- 1.0
- "1.0"
- "1"
- 1
- x
Answers to practice problems
- C
- A
- D
- B
- A
def floor_to_string (number):
number_floor = math.floor(number)
number_string = str(number_floor)
return number_string