2.7.EXAMPLE PROGRAM:FUTURE VALUE 23 $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(print statement,Section 2.4) print "This program calculates the future value of a 10-year investment" Input the amount of the principal(input statement,Section 2.5.2) principal input("Enter the initial principal:" Input the annualized percentage rate(input statement,Section 2.5.2) apr input("Enter the annualized interest rate:" Repeat 10 times:(counted loop,Section 2.6) fori in range(10): Calculate principal=principal *(1+apr)(simple assignment statement,Section 2.5.1) principalprincipal (1 apr) Output the value of the principal(print statement,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 carried 10 years into the future
2.7. EXAMPLE PROGRAM: FUTURE VALUE 23 $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 (print statement, Section 2.4) print "This program calculates the future value of a 10-year investment" Input the amount of the principal (input statement, Section 2.5.2) principal = input("Enter the initial principal: ") Input the annualized percentage rate (input statement, 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 (print statement, 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 # carried 10 years into the future
24 CHAPTER 2.WRITING SIMPLE PROGRAMS #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 the chaos.py program(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 the convert.py program(Section 2.2)to print an introduction. 4.Modify the avg2.py program(Section 2.5.3)to find the average of three exam scores. 5.Modify the futval.py program(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 the convert.py program(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.py program(Section 2.2)so that it computes and prints a table of Celsius temperatures and the Fahrenheit equivalents every 10 degrees from OC to 100C. 8.Write a program that converts from Fahrenheit to Celsius. 9.Modify the futval.py program(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: principalprincipal/(1+inflation)
24 CHAPTER 2. WRITING SIMPLE PROGRAMS # 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 the chaos.py program (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, assignment, input, loop, etc.) 3. A user-friendly program should print an introduction that tells the user what the program does. Modify the convert.py program (Section 2.2) to print an introduction. 4. Modify the avg2.py program (Section 2.5.3) to find the average of three exam scores. 5. Modify the futval.py program (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 the convert.py program (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.py program (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 the futval.py program (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: principal = principal/(1 + inflation)
Chapter 3 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)areare whole numbers;they don't have any fractional part.The values of the coins(.25,.10,.05,.01) 25
Chapter 3 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) 25
26 CHAPTER 3.COMPUTING WITH NUMBERS 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 floar) 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'> >>>myF1oat=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 3 quarters,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
26 CHAPTER 3. COMPUTING WITH NUMBERS 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 3 1 2 quarters, 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.2.USING THE MATH LIBRARY 27 >>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 expression 9.0 /5.0 in her tempera- ture conversion program rather than 9 /5.Now you know why.The former gives the correct multiplier of 18,while the latter yields just 1.since 5 gozinta 9 just once. 3.2 Using the Math Library Besides the operations listed in Table 3.1,Python provides many other useful mathematical functions in a special math library.A library is just a module that contains some useful definitions.Our next program illustrates the use of this library to compute the roots of quadratic equations. Aqdratiqo has the fom.Such an equation has two solutions for the vae of x given by the quadratic formula: -b±Vb-4ac X 2a Let's write a program that can find the solutions to a quadratic equation.The input to the program will be the values of the coefficients a,b,and c.The outputs are the two values given by the quadratic formula.Here's a program that does the job. quadratic.py A program that computes the real roots of a quadratic equation. Illustrates use of the math library. Note:this program crashes if the equation has no real roots. import math Makes the math library available. def main(): print "This program finds the real solutions to a quadratic" print a,b,c input ("Please enter the coefficients (a,b,c):" discRoot math.sgrt(b b-4 a c)
3.2. USING THE MATH LIBRARY 27 >>> 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 expression 9.0 / 5.0 in her temperature conversion program rather than 9 / 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. 3.2 Using the Math Library Besides the operations listed in Table 3.1, Python provides many other useful mathematical functions in a special math library. A library is just a module that contains some useful definitions. Our next program illustrates the use of this library to compute the roots of quadratic equations. A quadratic equation has the form ax2 ✂ bx ✂ c 0. Such an equation has two solutions for the value of x given by the quadratic formula: x ✂b ✂✁b 2 ✂ 4ac 2a Let’s write a program that can find the solutions to a quadratic equation. The input to the program will be the values of the coefficients a, b, and c. The outputs are the two values given by the quadratic formula. Here’s a program that does the job. # quadratic.py # A program that computes the real roots of a quadratic equation. # Illustrates use of the math library. # Note: this program crashes if the equation has no real roots. import math # Makes the math library available. def main(): print "This program finds the real solutions to a quadratic" print a, b, c = input("Please enter the coefficients (a, b, c): ") discRoot = math.sqrt(b * b - 4 * a * c)