14 CHAPTER 2.WRITING SIMPLE PROGRAMS Fortunately,Suzie has an idea to solve the problem.Being a computer science major,she never goes anywhere without her laptop computer.She thinks it might be possible that a computer program could help her out. Suzie begins with the requirements of her problem.In this case,the problem is pretty clear:the radio an- nouncer gives temperatures in degrees Celsius,but Suzie only comprehends temperatures that are in degrees Fahrenheit.That's the crux of the problem. Next,Suzie considers the specifications of a program that might help her out.What should the input be?She decides that her program will allow her to type in the temperature in degrees Celsius.And the output?The program will display the temperature converted into degrees Fahrenheit.Now she needs to specify the exact relationship of the output to the input.Suzie does some quick figuring to derive the formula F.(9/5)C+32(Can you see how?).That seems an adequate specification. Notice that this describes one of many possible programs that could solve this problem.If Suzie had background in the field of Artificial Intelligence (Al),she might consider writing a program that would actually listen to the radio announcer to get the current temperature using speech recognition algorithms.For output,she might have the computer control a robot that goes to her closet and picks an appropriate outfit based on the converted temperature.This would be a much more ambitious project,to say the least! Certainly the robot program would also solve the problem identified in the requirements.The purpose of specification is to decide exactly what this particular program will do to solve a problem.Suzie knows better than to just dive in and start writing a program without first having a clear idea of what she is trying to build. Suzie is now ready to design an algorithm for her problem.She immediately realizes that this is a simple algorithm that follows a standard pattern:Input,Process,Output (IPO).Her program will prompt the user for some input information(the Celsius temperature),process it to convert to a Fahrenheit temperature,and then output the result by displaying it on the computer screen. Suzie could write her algorithm down in a computer language.However,the precision of writing it out formally tends to stifle the creative process of developing the algorithm.Instead,she writes her algorithm using pseudocode.Pseudocode is just precise English that describes what a program does.It is meant to communicate algorithms without all the extra mental overhead of getting the details right in any particular programming language. Here is Suzie's completed algorithm: Input the temperature in degrees Celsius (call it celsius) Calculate fahrenheit as 9/5 celsius 32 Output fahrenheit The next step is to translate this design into a Python program.This is straightforward,as each line of the algorithm turns into a corresponding line of Python code. convert.py A program to convert Celsius temps to Fahrenheit by:Suzie Programmer def main(): celsius input("What is the Celsius temperature?" fahrenheit =9.0/5.0 celsius 32 print "The temperature is",fahrenheit,"degrees Fahrenheit." main() See if you can figure out what each line of this program does.Don't worry if some parts are a bit confusing. They will be discussed in detail in the next section. After completing her program,Suzie tests it to see how well it works.She uses some inputs for which she knows the correct answers.Here is the output from two of her tests. What is the Celsius temperature?0 The temperature is 32.0 degrees fahrenheit
14 CHAPTER 2. WRITING SIMPLE PROGRAMS Fortunately, Suzie has an idea to solve the problem. Being a computer science major, she never goes anywhere without her laptop computer. She thinks it might be possible that a computer program could help her out. Suzie begins with the requirements of her problem. In this case, the problem is pretty clear: the radio announcer gives temperatures in degrees Celsius, but Suzie only comprehends temperatures that are in degrees Fahrenheit. That’s the crux of the problem. Next, Suzie considers the specifications of a program that might help her out. What should the input be? She decides that her program will allow her to type in the temperature in degrees Celsius. And the output? The program will display the temperature converted into degrees Fahrenheit. Now she needs to specify the exact relationship of the output to the input. Suzie does some quick figuring to derive the formula F 9✁ 5✁ C ✂ 32 (Can you see how?). That seems an adequate specification. Notice that this describes one of many possible programs that could solve this problem. If Suzie had background in the field of Artificial Intelligence (AI), she might consider writing a program that would actually listen to the radio announcer to get the current temperature using speech recognition algorithms. For output, she might have the computer control a robot that goes to her closet and picks an appropriate outfit based on the converted temperature. This would be a much more ambitious project, to say the least! Certainly the robot program would also solve the problem identified in the requirements. The purpose of specification is to decide exactly what this particular program will do to solve a problem. Suzie knows better than to just dive in and start writing a program without first having a clear idea of what she is trying to build. Suzie is now ready to design an algorithm for her problem. She immediately realizes that this is a simple algorithm that follows a standard pattern: Input, Process, Output (IPO). Her program will prompt the user for some input information (the Celsius temperature), process it to convert to a Fahrenheit temperature, and then output the result by displaying it on the computer screen. Suzie could write her algorithm down in a computer language. However, the precision of writing it out formally tends to stifle the creative process of developing the algorithm. Instead, she writes her algorithm using pseudocode. Pseudocode is just precise English that describes what a program does. It is meant to communicate algorithms without all the extra mental overhead of getting the details right in any particular programming language. Here is Suzie’s completed algorithm: Input the temperature in degrees Celsius (call it celsius) Calculate fahrenheit as 9/5 celsius + 32 Output fahrenheit The next step is to translate this design into a Python program. This is straightforward, as each line of the algorithm turns into a corresponding line of Python code. # convert.py # A program to convert Celsius temps to Fahrenheit # by: Suzie Programmer def main(): celsius = input("What is the Celsius temperature? ") fahrenheit = 9.0 / 5.0 * celsius + 32 print "The temperature is", fahrenheit, "degrees Fahrenheit." main() See if you can figure out what each line of this program does. Don’t worry if some parts are a bit confusing. They will be discussed in detail in the next section. After completing her program, Suzie tests it to see how well it works. She uses some inputs for which she knows the correct answers. Here is the output from two of her tests. What is the Celsius temperature? 0 The temperature is 32.0 degrees fahrenheit
2.3.ELEMENTS OF PROGRAMS 15 What is the Celsius temperature?100 The temperature is 212.0 degrees fahrenheit. You can see that Suzie used the values of 0 and 100 to test her program.It looks pretty good,and she is satisfied with her solution.Apparently,no debugging is necessary. 2.3 Elements of Programs Now that you know something about the programming process,you are almost ready to start writing programs on your own.Before doing that,though,you need a more complete grounding in the fundamentals of Python. The next few sections will discuss technical details that are essential to writing correct programs.This material can seem a bit tedious,but you will have to master these basics before plunging into more interesting waters. 2.3.1 Names You have already seen that names are an important part of programming.We give names to modules(e.g., convert)and to the functions within modules(e.g.,main).Variables are used to give names to values(e.g., celsius and fahrenheit).Technically,all these names are called identifiers.Python has some rules about how identifiers are formed.Every identifier must begin with a letter or underscore(the""character) which may be followed by any sequence of letters,digits,or underscores.This implies that a single identifier cannot contain any spaces. According to these rules,all of the following are legal names in Python: X celsius spam spam2 SpamAndEggs Spam and Eggs Identifiers are case-sensitive,so spam,Spam,sPam,and SPAM are all different names to Python.For the most part,programmers are free to choose any name that conforms to these rules.Good programmers always try to choose names that describe the thing being named. One other important thing to be aware of is that some identifiers are part of Python itself.These names are called reserved words and cannot be used as ordinary identifiers.The complete list of Python reserved words is shown in Table 2.1. and del for IS raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print Table 2.1:Python Reserved Words. 2.3.2 Expressions Programs manipulate data.The fragments of code that produce or calculate new data values are called expressions.So far our program examples have dealt mostly with numbers,so I'll use numeric data to illustrate expressions
2.3. ELEMENTS OF PROGRAMS 15 What is the Celsius temperature? 100 The temperature is 212.0 degrees fahrenheit. You can see that Suzie used the values of 0 and 100 to test her program. It looks pretty good, and she is satisfied with her solution. Apparently, no debugging is necessary. 2.3 Elements of Programs Now that you know something about the programming process, you are almost ready to start writing programs on your own. Before doing that, though, you need a more complete grounding in the fundamentals of Python. The next few sections will discuss technical details that are essential to writing correct programs. This material can seem a bit tedious, but you will have to master these basics before plunging into more interesting waters. 2.3.1 Names You have already seen that names are an important part of programming. We give names to modules (e.g., convert) and to the functions within modules(e.g., main). Variables are used to give names to values (e.g., celsius and fahrenheit). Technically, all these names are called identifiers. Python has some rules about how identifiers are formed. Every identifier must begin with a letter or underscore (the “ ” character) which may be followed by any sequence of letters, digits, or underscores. This implies that a single identifier cannot contain any spaces. According to these rules, all of the following are legal names in Python: x celsius spam spam2 SpamAndEggs Spam_and_Eggs Identifiers are case-sensitive, so spam, Spam, sPam, and SPAM are all different names to Python. For the most part, programmers are free to choose any name that conforms to these rules. Good programmers always try to choose names that describe the thing being named. One other important thing to be aware of is that some identifiers are part of Python itself. These names are called reserved words and cannot be used as ordinary identifiers. The complete list of Python reserved words is shown in Table 2.1. and del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass yield def finally in print Table 2.1: Python Reserved Words. 2.3.2 Expressions Programs manipulate data. The fragments of code that produce or calculate new data values are called expressions. So far our program examples have dealt mostly with numbers, so I’ll use numeric data to illustrate expressions
16 CHAPTER 2.WRITING SIMPLE PROGRAMS The simplest kind of expression is a literal.A literal is used to indicate a specific value.In chaos.py you can find the numbers 3.9 and 1.The convert.py program contains 9.0,5.0,and 32.These are all examples of numeric literals,and their meaning is obvious:32 represents,well,32. A simple identifier can also be an expression.We use identifiers as variables to give names to values. When an identifier appears in an expression,this value is retrieved to provide a result for the expression. Here is an interaction with the Python interpreter that illustrates the use of variables as expressions. >>>x=5 >>>X 5 >>print x 5 >>print spam Traceback (innermost last): File "<pyshell#34>",line 1,in print spam NameError:spam >>> First the variable x is assigned the value 5(using the numeric literal 5).The next line has Python evaluate the expression x.Python spits back 5,which is the value that was just assigned to x.Of course,we get the same result when we put x in a print statement.The last example shows what happens when we use a variable that has not been assigned a value.Python cannot find a value,so it reports a Name Error.This says that there is no value with that name.A variable must always be assigned a value before it can be used in an expression. More complex and interesting expressions can be constructed by combining simpler expressions with operators.For numbers,Python provides the normal set of mathematical operations:addition,subtraction, multiplication,division,and exponentiation.The corresponding Python operators are:+,-,*/and * Here are some examples of complex expressions from chaos.py and convert.py 3.9*x*(1-) 9.0/5.0*ce1sius+32 Spaces are irrelevant within an expression.The last expression could have been written 9.0/5.0*celsius+32 and the result would be exactly the same.Usually it's a good idea to place some spaces in expressions to make them easier to read. Python's mathematical operators obey the same rules of precedence and associativity that you learned in your math classes,including using parentheses to modify the order of evaluation.You should have lit- tle trouble constructing complex expressions in your own programs.Do keep in mind that only the round parentheses are allowed in expressions,but you can nest them if necessary to create expressions like this ((x1-x2)/2*n)+(spam/k**3) If you are reading carefully,you may be curious why,in her temperature conversion program,Suzie Programmer chose to write 9.0/5.0 rather than 9/5.Both of these are legal expressions,but they give different results.This mystery will be discussed in Chapter 3.If you can't stand the wait,try them out for yourself and see if you can figure out what's going on. 2.4 Output Statements Now that you have the basic building blocks,identifier and expression,you are ready for a more complete description of various Python statements.You already know that you can display information on the screen using Python's print statement.But what exactly can be printed?Python,like all programming languages, has a precise set ofrules for the syntax (form)and semantics(meaning)ofeach statement.Computer scientists have developed sophisticated notations called meta-languages for describing programming languages.In this book we will rely on a simple template notation to illustrate the syntax of statements. Here are the possible forms of the print statement:
16 CHAPTER 2. WRITING SIMPLE PROGRAMS The simplest kind of expression is a literal. A literal is used to indicate a specific value. In chaos.py you can find the numbers 3.9 and 1. The convert.py program contains 9.0, 5.0, and 32. These are all examples of numeric literals, and their meaning is obvious: 32 represents, well, 32. A simple identifier can also be an expression. We use identifiers as variables to give names to values. When an identifier appears in an expression, this value is retrieved to provide a result for the expression. Here is an interaction with the Python interpreter that illustrates the use of variables as expressions. >>> x = 5 >>> x 5 >>> print x 5 >>> print spam Traceback (innermost last): File "<pyshell#34>", line 1, in ? print spam NameError: spam >>> First the variable x is assigned the value 5 (using the numeric literal 5). The next line has Python evaluate the expression x. Python spits back 5, which is the value that was just assigned to x. Of course, we get the same result when we put x in a print statement. The last example shows what happens when we use a variable that has not been assigned a value. Python cannot find a value, so it reports a Name Error. This says that there is no value with that name. A variable must always be assigned a value before it can be used in an expression. More complex and interesting expressions can be constructed by combining simpler expressions with operators. For numbers, Python provides the normal set of mathematical operations: addition, subtraction, multiplication, division, and exponentiation. The corresponding Python operators are: +, -, *, /, and **. Here are some examples of complex expressions from chaos.py and convert.py 3.9 * x * (1 - x) 9.0 / 5.0 * celsius + 32 Spaces are irrelevant within an expression. The last expression could have been written 9.0/5.0*celsius+32 and the result would be exactly the same. Usually it’s a good idea to place some spaces in expressions to make them easier to read. Python’s mathematical operators obey the same rules of precedence and associativity that you learned in your math classes, including using parentheses to modify the order of evaluation. You should have little trouble constructing complex expressions in your own programs. Do keep in mind that only the round parentheses are allowed in expressions, but you can nest them if necessary to create expressions like this. ((x1 - x2) / 2*n) + (spam / k**3) If you are reading carefully, you may be curious why, in her temperature conversion program, Suzie Programmer chose to write 9.0/5.0 rather than 9/5. Both of these are legal expressions, but they give different results. This mystery will be discussed in Chapter 3. If you can’t stand the wait, try them out for yourself and see if you can figure out what’s going on. 2.4 Output Statements Now that you have the basic building blocks, identifier and expression, you are ready for a more complete description of various Python statements. You already know that you can display information on the screen using Python’s print statement. But what exactly can be printed? Python, like all programming languages, has a precise set of rulesfor the syntax (form) and semantics (meaning) of each statement. Computerscientists have developed sophisticated notations called meta-languages for describing programming languages. In this book we will rely on a simple template notation to illustrate the syntax of statements. Here are the possible forms of the print statement:
2.5.ASSIGNMENT STATEMENTS 17 print print <expr> print <expr>,<expr>,...,<expr> print <expr>,<expr>,...<expr>, In a nutshell,these templates show that a print statement consists of the keyword print followed by zero or more expressions,which are separated by commas.The angle bracket notation (<>)is used to indicate "slots"that are filled in by other fragments of Python code.The name inside the brackets indicate what is missing;expr stands for an expression.The ellipses("..")indicate an indefinite series (of expressions, in this case).You don't actually type the dots.The fourth version shows that a print statement may be optionally ended with a comma.That is all there is to know about the syntax of print. As far as semantics,a print statement displays information in textual form.Any supplied expressions are evaluated left to right,and the resulting values are displayed on a single line of output in a left-to-right fashion.A single blank space character is placed between the displayed values. Normally,successive print statements will display on separate lines of the screen.A bare print(first version above)can be used to get a blank line of output.If a print statement ends with a comma (fourth version),a final space is appended to the line,but the output does not advance to the next line.Using this method,multiple print statements can be used to generate a single line of output. Putting it all together,this sequence of print statements print 3+4 print 3,4,3 +4 print print 3,4, print 3+4 print "The answer is",3 +4 produces this output 个 347 347 The answer is 7 That last print statement may be a bit confusing.According to the syntax templates above,print requires a sequence of expressions.That means "The answer is"must be an expression.In fact,it is an expression,but it doesn't produce a number.Instead,it produces another kind of data called a string. A sequence of characters enclosed in quotes is a string literal.Strings will be discussed in detail in a later chapter.For now,consider this a convenient way of labeling output. 2.5 Assignment Statements 2.5.1 Simple Assignment One of the most important kinds of statements in Python is the assignment statement.We've already seen a number of these in our previous examples.The basic assignment statement has this form: <variable><expr> Here variable is an identifier and expr is an expression.The semantics of the assignment is that the expression on the right side is evaluated to produce a value,which is then associated with the variable named on the left side Here are some of the assignments we've already seen. x=3.9*×*(1-x) fahrenheit =9.0 /5.0 celsius 32 x=5
2.5. ASSIGNMENT STATEMENTS 17 print print <expr> print <expr>, <expr>, ..., <expr> print <expr>, <expr>, ..., <expr>, In a nutshell, these templates show that a print statement consists of the keyword print followed by zero or more expressions, which are separated by commas. The angle bracket notation (✁) is used to indicate “slots” that are filled in by other fragments of Python code. The name inside the brackets indicate what is missing; expr stands for an expression. The ellipses (“...”) indicate an indefinite series (of expressions, in this case). You don’t actually type the dots. The fourth version shows that a print statement may be optionally ended with a comma. That is all there is to know about the syntax of print. As far as semantics, a print statement displays information in textual form. Any supplied expressions are evaluated left to right, and the resulting values are displayed on a single line of output in a left-to-right fashion. A single blank space character is placed between the displayed values. Normally, successive print statements will display on separate lines of the screen. A bare print (first version above) can be used to get a blank line of output. If a print statement ends with a comma (fourth version), a final space is appended to the line, but the output does not advance to the next line. Using this method, multiple print statements can be used to generate a single line of output. Putting it all together, this sequence of print statements print 3+4 print 3, 4, 3 + 4 print print 3, 4, print 3+4 print "The answer is", 3 + 4 produces this output 7 3 4 7 3 4 7 The answer is 7 That last print statement may be a bit confusing. According to the syntax templates above, print requires a sequence of expressions. That means "The answer is" must be an expression. In fact, it is an expression, but it doesn’t produce a number. Instead, it produces another kind of data called a string. A sequence of characters enclosed in quotes is a string literal. Strings will be discussed in detail in a later chapter. For now, consider this a convenient way of labeling output. 2.5 Assignment Statements 2.5.1 Simple Assignment One of the most important kinds of statements in Python is the assignment statement. We’ve already seen a number of these in our previous examples. The basic assignment statement has this form: <variable> = <expr> Here variable is an identifier and expr is an expression. The semantics of the assignment is that the expression on the right side is evaluated to produce a value, which is then associated with the variable named on the left side. Here are some of the assignments we’ve already seen. x = 3.9 * x * (1 - x) fahrenheit = 9.0 / 5.0 * celsius + 32 x = 5
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