2.5.ASSIGNMENT STATEMENTS 19 2.5.3 Simultaneous Assignment There is an alternative form of the assignment statement that allows us to calculate several values all at the same time.It looks like this: <var>,<var>,...,<var><expr>,<expr>,...,<expr> This is called simultaneous assignment.Semantically,this tells Python to evaluate all the expressions on the right-hand side and then assign these values to the corresponding variables named on the left-hand side. Here's an example. sum,diff x+y,x-y Here sum would get the sum of x and y and diff would get the difference This form of assignment seems strange at first,but it can prove remarkably useful.Here's an example. Suppose you have two variables x and y and you want to swap the values.That is,you want the value currently stored in x to be in y and the value that is currently in y to be stored in x.At first,you might think this could be done with two simple assignments. x=y y=x This doesn't work.We can trace the execution of these statements step-by-step to see why. Suppose x and y start with the values 2 and 4.Let's examine the logic of the program to see how the variables change.The following sequence uses comments to describe what happens to the variables as these two statements are executed. variables x y initial values 2 4 x=y #now 44 y=x final 44 See how the first statement clobbers the original value of x by assigning to it the value of y?When we then assign x to y in the second step,we just end up with two copies of the original y value. One way to make the swap work is to introduce an additional variable that temporarily remembers the original value of x. temp x x =y y=temp Let's walk-through this sequence to see how it works. variables x y temp initial values 2 4 no value yet temp x 242 x=y 44 3 y temp 422 As you can see from the final values ofx and y,the swap was successful in this case. This sort of three-way shuffle is common in other programming languages.In Python,the simultaneous assignment statement offers an elegant alternative.Here is a simpler Python equivalent: XI y =y x
2.5. ASSIGNMENT STATEMENTS 19 2.5.3 Simultaneous Assignment There is an alternative form of the assignment statement that allows us to calculate several values all at the same time. It looks like this: <var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr> This is called simultaneous assignment. Semantically, this tells Python to evaluate all the expressions on the right-hand side and then assign these values to the corresponding variables named on the left-hand side. Here’s an example. sum, diff = x+y, x-y Here sum would get the sum of x and y and diff would get the difference. This form of assignment seems strange at first, but it can prove remarkably useful. Here’s an example. Suppose you have two variables x and y and you want to swap the values. That is, you want the value currently stored in x to be in y and the value that is currently in y to be stored in x. At first, you might think this could be done with two simple assignments. x = y y = x This doesn’t work. We can trace the execution of these statements step-by-step to see why. Suppose x and y start with the values 2 and 4. Let’s examine the logic of the program to see how the variables change. The following sequence uses comments to describe what happens to the variables as these two statements are executed. # variables x y # initial values 2 4 x = y # now 4 4 y = x # final 4 4 See how the first statement clobbers the original value of x by assigning to it the value of y? When we then assign x to y in the second step, we just end up with two copies of the original y value. One way to make the swap work is to introduce an additional variable that temporarily remembers the original value of x. temp = x x = y y = temp Let’s walk-through this sequence to see how it works. # variables x y temp # initial values 2 4 no value yet temp = x # 2 4 2 x = y # 4 4 2 y = temp # 4 2 2 As you can see from the final values of x and y, the swap was successful in this case. This sort of three-way shuffle is common in other programming languages. In Python, the simultaneous assignment statement offers an elegant alternative. Here is a simpler Python equivalent: x, y = y, x
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