18 CHAPTER 2.WRITING SIMPLE PROGRAMS A variable can be assigned many times.It always retains the value of the most recent assignment.Here is an interactive Python session that demonstrates the point: >>myVar =0 >>myvar 0 >>myVar 7 >>myvar 1 >>myVar myvar +1 >>myvar 8 The last assignment statement shows how the current value of a variable can be used to update its value.In this case I simply added one to the previous value.The chaos.py program from Chapter 1 did something similar,though a bit more complex.Remember,the values of variables can change:that's why they're called variables. 2.5.2 Assigning Input The purpose of an input statement is to get some information from the user of a program and store it into a variable.Some programming languages have a special statement to do this.In Python,input is accomplished using an assignment statement combined with a special expression called input.This template shows the standard form <variable>=input (<prompt>) Here prompt is an expression that serves to prompt the user for input,this is almost always a string literal (i.e.,some text inside of quotation marks). When Python encounters an input expression,it evaluates the prompt and displays the result of the prompt on the screen.Python then pauses and waits for the user to type an expression and press the <Enter>key.The expression typed by the user is then evaluated to produce the result of the input. This sounds complicated,but most uses of input are straightforward.In our example programs,input statements are used to get numbers from the user. x input("Please enter a number between 0 and 1:" celsius input("What is the Celsius temperature?" If you are reading programs carefully,you probably noticed the blank space inside the quotes at the end of these prompts.I usually put a space at the end of a prompt so that the input that the user types does not start right next to the prompt.Putting a space in makes the interaction easier to read and understand. Although these two examples specifically prompt the user to enter a number,a number is just a numeric literal-a simple Python expression.In fact,any valid expression would be just as acceptable.Consider the following interaction with the Python interpreter. >>ans input("Enter an expression:" Enter an expression:3 +4 *5 >>print ans 23 >>> Here,when prompted to enter an expression,the user typed"3+4 5."Python evaluated this expression and stored the value in the variable ans.When printed,we see that ans got the value 23 as expected. In a way,the input is like a delayed expression.The example interaction produced exactly the same result as if we had simply done ans =3 +4 5.The difference is that the expression was supplied at the time the statement was executed instead of being determined when the statement was written by the programmer.Thus,the user can supply formulas for a program to evaluate
18 CHAPTER 2. WRITING SIMPLE PROGRAMS A variable can be assigned many times. It always retains the value of the most recent assignment. Here is an interactive Python session that demonstrates the point: >>> myVar = 0 >>> myVar 0 >>> myVar = 7 >>> myVar 7 >>> myVar = myVar + 1 >>> myVar 8 The last assignment statement shows how the current value of a variable can be used to update its value. In this case I simply added one to the previous value. The chaos.py program from Chapter 1 did something similar, though a bit more complex. Remember, the values of variables can change; that’s why they’re called variables. 2.5.2 Assigning Input The purpose of an input statement is to get some information from the user of a program and store it into a variable. Some programming languages have a special statement to do this. In Python, input is accomplished using an assignment statement combined with a special expression called input. This template shows the standard form. <variable> = input(<prompt>) Here prompt is an expression that serves to prompt the user for input; this is almost always a string literal (i.e., some text inside of quotation marks). When Python encounters an input expression, it evaluates the prompt and displays the result of the prompt on the screen. Python then pauses and waits for the user to type an expression and press the Enter key. The expression typed by the user is then evaluated to produce the result of the input. This sounds complicated, but most uses of input are straightforward. In our example programs, input statements are used to get numbers from the user. x = input("Please enter a number between 0 and 1: ") celsius = input("What is the Celsius temperature? ") If you are reading programs carefully, you probably noticed the blank space inside the quotes at the end of these prompts. I usually put a space at the end of a prompt so that the input that the user types does not start right next to the prompt. Putting a space in makes the interaction easier to read and understand. Although these two examples specifically prompt the user to enter a number, a number is just a numeric literal—a simple Python expression. In fact, any valid expression would be just as acceptable. Consider the following interaction with the Python interpreter. >>> ans = input("Enter an expression: ") Enter an expression: 3 + 4 * 5 >>> print ans 23 >>> Here, when prompted to enter an expression, the user typed “3 + 4 * 5.” Python evaluated this expression and stored the value in the variable ans. When printed, we see that ans got the value 23 as expected. In a way, the input is like a delayed expression. The example interaction produced exactly the same result as if we had simply done ans = 3 + 4 * 5. The difference is that the expression was supplied at the time the statement was executed instead of being determined when the statement was written by the programmer. Thus, the user can supply formulas for a program to evaluate
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