Chapter 2 Writing Simple Programs As you saw in the previous chapter,it is easy to run programs that have already been written.The hard part is actually coming up with the program in the first place.Computers are very literal,and they must be told what to do right down to the last detail.Writing large programs is a daunting task.It would be almost impossible without a systematic approach. 2.1 The Software Development Process The process of creating a program is often broken down into stages according to the information that is produced in each phase.In a nutshell,here's what you should do. Formulate Requirements Figure out exactly what the problem to be solved is.Try to understand as much as possible about it.Until you really know what the problem is,you cannot begin to solve it. Determine Specifications Describe exactly what your program will do.At this point,you should not worry about how your program will work,but rather with deciding exactly what it will accomplish.For simple programs this involves carefully describing what the inputs and outputs of the program will be and how they relate to each other. Create a Design Formulate the overall structure of the program.This is where the how of the program gets worked out.The main task is to design the algorithm(s)that will meet the specifications. Implement the Design Translate the design into a computer language and put it into the computer.In this book,we will be implementing our algorithms as Python programs. Test/Debug the Program Try out your program and see if it works as expected.If there are any errors(often called bugs),then you should go back and fix them.The process of locating and fixing errors is called debugging a program. Maintain the Program Continue developing the program in response to the needs of your users.Most programs are never really finished;they keep evolving over years of use. 2.2 Example Program:Temperature Converter Let's go through the steps of the software development process with a simple real-world example.Suzie Programmer has a problem.Suzie is an American computer science student spending a year studying in Europe.She has no problems with language,as she is fluent in many languages(including Python).Her problem is that she has a hard time figuring out the temperature in the morning so that she knows how to dress for the day.Suzie listens to the weather report each morning,but the temperatures are given in degrees Celsius,and she is used to Fahrenheit. 13
Chapter 2 Writing Simple Programs As you saw in the previous chapter, it is easy to run programs that have already been written. The hard part is actually coming up with the program in the first place. Computers are very literal, and they must be told what to do right down to the last detail. Writing large programs is a daunting task. It would be almost impossible without a systematic approach. 2.1 The Software Development Process The process of creating a program is often broken down into stages according to the information that is produced in each phase. In a nutshell, here’s what you should do. Formulate Requirements Figure out exactly what the problem to be solved is. Try to understand as much as possible about it. Until you really know what the problem is, you cannot begin to solve it. Determine Specifications Describe exactly what your program will do. At this point, you should not worry about how your program will work, but rather with deciding exactly what it will accomplish. For simple programs this involves carefully describing what the inputs and outputs of the program will be and how they relate to each other. Create a Design Formulate the overall structure of the program. This is where the how of the program gets worked out. The main task is to design the algorithm(s) that will meet the specifications. Implement the Design Translate the design into a computer language and put it into the computer. In this book, we will be implementing our algorithms as Python programs. Test/Debug the Program Try out your program and see if it works as expected. If there are any errors (often called bugs), then you should go back and fix them. The process of locating and fixing errors is called debugging a program. Maintain the Program Continue developing the program in response to the needs of your users. Most programs are never really finished; they keep evolving over years of use. 2.2 Example Program: Temperature Converter Let’s go through the steps of the software development process with a simple real-world example. Suzie Programmer has a problem. Suzie is an American computer science student spending a year studying in Europe. She has no problems with language, as she is fluent in many languages (including Python). Her problem is that she has a hard time figuring out the temperature in the morning so that she knows how to dress for the day. Suzie listens to the weather report each morning, but the temperatures are given in degrees Celsius, and she is used to Fahrenheit. 13
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