• No results found

Example Program: Future Value

In document Python Programming (Page 30-35)

Let’s close the chapter with one more example of the programming process in action. We want to develop a program to determine the future value of an investment. Let’s start with an analysis of the problem (require- ments). You know that money that is deposited in a bank account earns interest, and this interest accumulates as the years pass. How much will an account be worth ten years from now? Obviously it depends on how much money we start with (the principal) and how much interest the account earns. Given the principal and the interest rate, a program should be able to calculate the value of the investment ten years into the future.

We continue by developing the exact specifications for the program. Recall, this is a description of what the program will do. What exactly should the inputs be? We need the user to enter the initial amount to invest, the principal. We will also need some indication of how much interest the account earns. This depends both on the interest rate and how often the interest is compounded. One simple way of handling this is to have the user enter an annualized percentage rate. Whatever the actual interest rate and compounding frequency, the annualized rate tells us how much the investment accrues in one year. If the annualized interest is 3%, then a

$100 investment will grow to $103 in one year’s time. How should the user represent an annualized rate of 3%? There are a number of reasonable choices. Let’s assume the user supplies a decimal, so the rate would be entered as 0.03.

This leads us to the following specification.

Program Future Value Inputs

principal The amount of money being invested in dollars.

apr The annualized percentage rate expressed as a decimal fraction. Output The value of the investment 10 years into the future.

Relationship Value after one year is given by principal 1 apr . This formula needs to be applied 10 times. Next we design an algorithm for the program. We’ll use pseudocode, so that we can formulate our ideas without worrying about all the rules of Python. Given our specification, the algorithm seems straightforward.

Print an introduction

Input the amount of the principal (principal) Input the annualized percentage rate (apr) Repeat 10 times:

principal = principal * (1 + apr) Output the value of principal

Now that we’ve thought the problem all the way through to pseudocode, it’s time to put our new Python knowledge to work and develop a program. Each line of the algorithm translates into a statement of Python. Print an introduction (printstatement, Section 2.4)

print "This program calculates the future value of a 10-year investment"

Input the amount of the principal (inputstatement, Section 2.5.2)

principal = input("Enter the initial principal: ")

Input the annualized percentage rate (inputstatement, Section 2.5.2)

apr = input("Enter the annualized interest rate: ")

Repeat 10 times: (counted loop, Section 2.6)

for i in range(10):

Calculate principal = principal * (1 + apr) (simple assignment statement, Section 2.5.1)

principal = principal * (1 + apr)

Output the value of the principal (printstatement, Section 2.4)

print "The amount in 10 years is:", principal

All of the statement types in this program have been discussed in detail in this chapter. If you have any questions, you should go back and review the relevant descriptions. Notice especially the counted loop pattern is used to apply the interest formula 10 times.

That about wraps it up. Here is the completed program.

# futval.py

# A program to compute the value of an investment

# by: John M. Zelle def main():

print "This program calculates the future value of a 10-year investment." principal = input("Enter the initial principal: ")

apr = input("Enter the annualized interest rate: ") for i in range(10):

principal = principal * (1 + apr)

print "The amount in 10 years is:", principal main()

Notice that I have added a few blank lines to separate the Input, Processing, and Output portions of the program. Strategically placed “white space” can help make your programs more readable.

That’s about it for this example; I leave the testing and debugging as an exercise for you.

2.8

Exercises

1. List and describe in your own words the six steps in the software development process.

2. Write out thechaos.pyprogram (Section 1.6) and identify the parts of the program as follows: Circle each identifier.

Underline each expression.

Put a comment at the end of each line indicating the type of statement on that line (output, as- signment, input, loop, etc.)

3. A user-friendly program should print an introduction that tells the user what the program does. Modify theconvert.pyprogram (Section 2.2) to print an introduction.

4. Modify theavg2.pyprogram (Section 2.5.3) to find the average of three exam scores.

5. Modify thefutval.pyprogram (Section 2.7) so that the number of years for the investment is also a user input. Make sure to change the final message to reflect the correct number of years.

6. Modify theconvert.pyprogram (Section 2.2) with a loop so that it executes 5 times before quitting (i.e., it converts 5 temperatures in a row).

7. Modify the convert.pyprogram (Section 2.2) so that it computes and prints a table of Celsius temperatures and the Fahrenheit equivalents every 10 degrees from 0C to 100C.

8. Write a program that converts from Fahrenheit to Celsius.

9. Modify thefutval.pyprogram (Section 2.7) so that it computes the actual purchasing power of the investment, taking inflation into account. The yearly rate of inflation will be a second input. The adjustment is given by this formula:

Computing with Numbers

When computers were first developed, they were seen primarily as number crunchers, and that is still an important application. As you have seen, problems that involve mathematical formulas are easy to translate into Python programs. This chapter takes a closer look at computations involving numeric calculations.

3.1

Numeric Data Types

The information that is stored and manipulated by computer programs is generically referred to as data. Different kinds of data will be stored and manipulated in different ways. Consider this program that calculates the value of loose change.

# change.py

# A program to calculate the value of some change in dollars

def main():

print "Change Counter" print

print "Please enter the count of each coin type." quarters = input("Quarters: ")

dimes = input("Dimes: ") nickels = input("Nickels: ") pennies = input("Pennies: ")

total = quarters * .25 + dimes * .10 + nickels * .05 + pennies * .01 print

print "The total value of your change is", total main()

Here is an example of the output.

Change Counter

Please enter the count of each coin type. Quarters: 5

Dimes: 3 Nickels: 4 Pennies: 6

The total value of your change is 1.81

This program actually manipulates two different kinds of numbers. The values entered by the user (5, 3, 4, 6) are are whole numbers; they don’t have any fractional part. The values of the coins (.25, .10, .05, .01)

are decimal fractions. Inside the computer, whole numbers and numbers that have fractional components are represented differently. Technically, we say that these are two different data types.

The data type of an object determines what values it can have and what operations can be performed on it. Whole numbers are represented using the integer data type (int for short). Values of type int can be positive or negative whole numbers. Numbers that can have fractional parts are represented as floating point (or float) values. So how do we tell whether a number is an int or a float? A numeric literal that does not contain a decimal point produces an int value, while a literal that has a decimal point is represented by a float (even if the fractional part is 0).

Python provides a special function called type that tells us the data type of any value. Here is an interaction with the Python interpreter showing the difference between int and float literals.

>>> type(3) <type ’int’> >>> type(3.14) <type ’float’> >>> type(3.0) <type ’float’> >>> myInt = -32 >>> type(myInt) <type ’int’> >>> myFloat = 32.0 >>> type(myFloat) <type ’float’>

You may be wondering why there are two different data types for numbers. One reason has to do with program style. Values that represent counts can’t be fractional; we can’t have 312quarters, for example. Using an int value tells the reader of a program that the value can’t be a fraction. Another reason has to do with the efficiency of various operations. The underlying algorithms that perform computer arithmetic are simpler, and therefore faster, for ints than the more general algorithms required for float values.

You should be warned that the float type only stores approximations. There is a limit to the precision, or accuracy, of the stored values. Since float values are not exact, while ints always are, your general rule of thumb should be: if you don’t absolutely need fractional values, use an int.

operator operation  addition  subtraction multiplication  division  exponentiation % remainder

abs() absolute value

Table 3.1: Python built-in numeric operations.

A value’s data type determines what operations can be used on it. As we have seen, Python supports the usual mathematical operations on numbers. Table 3.1 summarizes these operations. Actually, this table is somewhat misleading since the two numeric data types have their own operations. When addition is performed on floats, the computer performs a floating point addition. Whereas, with ints, the computer performs an integer addition.

Consider the following interaction with Python:

>>> 3.0 + 4.0 7.0

>>> 3 + 4 7

>>> 3.0 * 4.0 12.0 >>> 3 * 4 12 >>> 10.0 / 3.0 3.33333333333 >>> 10 / 3 3 >>> 10 % 3 1 >>> abs(5) 5 >>> abs(-3.5) 3.5

Notice how operations on floats produce floats, and operations on ints produce ints. Most of the time, we don’t have to worry about what type of operation is being performed; for example, integer addition produces pretty much the same result as floating point addition.

However, in the case of division, the results are quite different. Integer division always produces an integer, discarding any fractional result. Think of integer division as “gozinta.” The expression,10 / 3

produces 3 because three gozinta (goes into) ten three times (with a remainder of one). The third to last example shows the remainder operation (%) in action. The remainder of dividing 10 by 3 is 1. The last two examples illustrate taking the absolute value of an expression.

You may recall from Chapter 2 that Suzie Programmer used the expression9.0 / 5.0in her tempera- ture conversion program rather than9 / 5. Now you know why. The former gives the correct multiplier of 1 8, while the latter yields just 1, since 5 gozinta 9 just once.

In document Python Programming (Page 30-35)