20 CHAPTER 2.WRITING SIMPLE PROGRAMS Because the assignment is simultaneous,it avoids wiping out one of the original values. Simultaneous assignment can also be used to get multiple values from the user in a single input.Con- sider this program for averaging exam scores: #avg2.py A simple program to average two exam scores Illustrates use of multiple input def main(): print "This program computes the average of two exam scores." scorel,score2 input ("Enter two scores separated by a comma:" average =(scorel +score2)/2.0 print "The average of the scores is:"average main() The program prompts for two scores separated by a comma.Suppose the user types 86,92.The effect of the input statement is then the same as if we had done this assignment: scorel,score2 86,92 We have gotten a value for each of the variables in one fell swoop.This example used just two values,but it could be generalized to any number of inputs. Of course,we could have just gotten the input from the user using separate input statements. scorel input("Enter the first score:" score2 input("Enter the second score:" In some ways this may be better,as the separate prompts are more informative for the user.In this example the decision as to which approach to take is largely a matter of taste.Sometimes getting multiple values in a single input provides a more intuitive user interface,so it is nice technique to have in your toolkit. 2.6 Definite Loops You already know that programmers use loops to execute a sequence ofstatements several times in succession The simplest kind of loop is called a definite loop.This is a loop that will execute a definite number of times. That is,at the point in the program when the loop begins,Python knows how many times to go around (or iterate)the body of the loop.For example,the Chaos program from Chapter 1 used a loop that always executed exactly ten times. for i in range(10): x=3.9*x*(1-x) print x This particular loop pattern is called a counted loop,and it is built using a Python for statement.Before considering this example in detail,let's take a look at what for loops are all about. A Python for loop has this general form. for <var>in <sequence>: <body> The body of the loop can be any sequence of Python statements.The start and end of the body is indicated by its indentation under the loop heading (the for <var>in <sequence>:part). The meaning of the for statement is a bit awkward to explain in words,but is very easy to understand. once you get the hang of it.The variable after the keyword for is called the loop index.It takes on
20 CHAPTER 2. WRITING SIMPLE PROGRAMS Because the assignment is simultaneous, it avoids wiping out one of the original values. Simultaneous assignment can also be used to get multiple values from the user in a single input. Consider this program for averaging exam scores: # avg2.py # A simple program to average two exam scores # Illustrates use of multiple input def main(): print "This program computes the average of two exam scores." score1, score2 = input("Enter two scores separated by a comma: ") average = (score1 + score2) / 2.0 print "The average of the scores is:", average main() The program prompts for two scores separated by a comma. Suppose the user types 86, 92. The effect of the input statement is then the same as if we had done this assignment: score1, score2 = 86, 92 We have gotten a value for each of the variables in one fell swoop. This example used just two values, but it could be generalized to any number of inputs. Of course, we could have just gotten the input from the user using separate input statements. score1 = input("Enter the first score: ") score2 = input("Enter the second score: ") In some ways this may be better, as the separate prompts are more informative for the user. In this example the decision as to which approach to take is largely a matter of taste. Sometimes getting multiple values in a single input provides a more intuitive user interface, so it is nice technique to have in your toolkit. 2.6 Definite Loops You already know that programmers use loopsto execute a sequence ofstatementsseveral times in succession. The simplest kind of loop is called a definite loop. This is a loop that will execute a definite number of times. That is, at the point in the program when the loop begins, Python knows how many times to go around (or iterate) the body of the loop. For example, the Chaos program from Chapter 1 used a loop that always executed exactly ten times. for i in range(10): x = 3.9 * x * (1 - x) print x This particular loop pattern is called a counted loop, and it is built using a Python for statement. Before considering this example in detail, let’s take a look at what for loops are all about. A Python for loop has this general form. for <var> in <sequence>: <body> The body of the loop can be any sequence of Python statements. The start and end of the body is indicated by its indentation under the loop heading (the for <var> in <sequence>: part). The meaning of the for statement is a bit awkward to explain in words, but is very easy to understand, once you get the hang of it. The variable after the keyword for is called the loop index. It takes on
2.6.DEFINITE LOOPS 21 each successive value in the sequence,and the statements in the body are executed once for each value. Usually,the sequence portion is a list of values.You can build a simple list by placing a sequence of expressions in square brackets.Some interactive examples help to illustrate the point: >>for i in[0,1,2,3]: print i 0 1 2 3 >>>for odd in[1,3,5,7,9]: print oddodd 1 9 25 49 81 You can see what is happening in these two examples.The body of the loop is executed using each successive value in the list.The length of the list determines the number of times the loop will execute.In the first example,the list contains the four values 0 through 3,and these successive values of i are simply printed.In the second example,odd takes on the values of the first five odd natural numbers,and the body of the loop prints the squares of these numbers. Now,let's go back to the example which began this section(from chaos.py)Look again at the loop heading: for i in range(10): Comparing this to the template for the for loop shows that the last portion,range (10)must be some kind of sequence.Let's see what the Python interpreter tells us. >>range(10) [0,1,2,3,4,5,6,7,8,9] Do you see what is happening here?The range function is a built-in Python command that simply produces a list of numbers.The loop using range(10)is exactly equivalent to one using a list of 10 numbers. fori1n[0,1,2,3,4,5,6,7,8,9]: In general,range (<expr>)will produce a list of numbers that starts with 0 and goes up to,but not including,the value of<expr>.If you think about it,you will see that the value of the expression determines the number of items in the resulting list.In chaos.py we did not even care what values the loop index variable used(since the value of i was not referred to anywhere in the loop body).We just needed a list of length 10 to make the body execute 10 times. As I mentioned above,this pattern is called a counted loop,and it is a very common way to use definite loops.When you want to do something in your program a certain number of times,use a for loop with a suitable range. for <variable>in range(<expr>): The value of the expression determines how many times the loop executes.The name of the index variable doesn't really matter much;programmers often use i or j as the loop index variable for counted loops.Just be sure to use an identifier that you are not using for any other purpose.Otherwise you might accidentally wipe out a value that you will need later
2.6. DEFINITE LOOPS 21 each successive value in the sequence, and the statements in the body are executed once for each value. Usually, the sequence portion is a list of values. You can build a simple list by placing a sequence of expressions in square brackets. Some interactive examples help to illustrate the point: >>> for i in [0,1,2,3]: print i 0 1 2 3 >>> for odd in [1, 3, 5, 7, 9]: print odd * odd 1 9 25 49 81 You can see what is happening in these two examples. The body of the loop is executed using each successive value in the list. The length of the list determines the number of times the loop will execute. In the first example, the list contains the four values 0 through 3, and these successive values of i are simply printed. In the second example, odd takes on the values of the first five odd natural numbers, and the body of the loop prints the squares of these numbers. Now, let’s go back to the example which began this section (from chaos.py) Look again at the loop heading: for i in range(10): Comparing this to the template for the for loop shows that the last portion, range(10) must be some kind of sequence. Let’s see what the Python interpreter tells us. >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Do you see what is happening here? The range function is a built-in Python command that simply produces a list of numbers. The loop using range(10) is exactly equivalent to one using a list of 10 numbers. for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: In general, range(<expr>) will produce a list of numbers that starts with 0 and goes up to, but not including, the value of <expr>. If you think about it, you will see that the value of the expression determines the number of items in the resulting list. In chaos.py we did not even care what values the loop index variable used (since the value of i was not referred to anywhere in the loop body). We just needed a list of length 10 to make the body execute 10 times. As I mentioned above, this pattern is called a counted loop, and it is a very common way to use definite loops. When you want to do something in your program a certain number of times, use a for loop with a suitable range. for <variable> in range(<expr>): The value of the expression determines how many times the loop executes. The name of the index variable doesn’t really matter much; programmers often use i or j as the loop index variable for counted loops. Just be sure to use an identifier that you are not using for any other purpose. Otherwise you might accidentally wipe out a value that you will need later
22 CHAPTER 2.WRITING SIMPLE PROGRAMS The interesting and useful thing about loops is the way that they alter the "flow of control"in a program. Usually we think of computers as executing a series of instructions in strict sequence.Introducing a loop causes Python to go back and do some statements over and over again.Statements like the for loop are called control structures because they control the execution of other parts of the program. Some programmers find it helpful to think of control structures in terms of pictures called flowcharts.A flowchart is a diagram that uses boxes to represent different parts of a program and arrows between the boxes to show the sequence of events when the program is running.Figure 2.1 depicts the semantics of the for loop as a flowchart. more items in <sequence> <var>=next item <body> Figure 2.1:Flowchart of a for loop If you are having trouble understanding the for loop,you might find it useful to study the flowchart. The diamond shape box in the flowchart represents a decision in the program.When Python gets thethe loop heading,it checks to see if there are any(more)items left if the sequence.If the answer is yes,the value of the loop index variable is set to the next item in the sequence,and then the loop body is executed.Once the body is complete,the program goes back to the loop heading and checks for another value in the sequence. The loop quits when there are no more items,and the program moves on to the statements that come after the loop 2.7 Example Program:Future Value 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
22 CHAPTER 2. WRITING SIMPLE PROGRAMS The interesting and useful thing about loops is the way that they alter the “flow of control” in a program. Usually we think of computers as executing a series of instructions in strict sequence. Introducing a loop causes Python to go back and do some statements over and over again. Statements like the for loop are called control structures because they control the execution of other parts of the program. Some programmers find it helpful to think of control structures in terms of pictures called flowcharts. A flowchart is a diagram that uses boxes to represent different parts of a program and arrows between the boxes to show the sequence of events when the program is running. Figure 2.1 depicts the semantics of the for loop as a flowchart. yes more items in <sequence> no <var> = next item <body> Figure 2.1: Flowchart of a for loop. If you are having trouble understanding the for loop, you might find it useful to study the flowchart. The diamond shape box in the flowchart represents a decision in the program. When Python gets the the loop heading, it checks to see if there are any (more) items left if the sequence. If the answer is yes, the value of the loop index variable is set to the next item in the sequence, and then the loop body is executed. Once the body is complete, the program goes back to the loop heading and checks for another value in the sequence. The loop quits when there are no more items, and the program moves on to the statements that come after the loop. 2.7 Example Program: Future Value 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 (requirements). 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
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)