xxviii Contents
xxviii Contents
Chapter 1 The way of the program The goal of this book is to teach you to think like a computer scientist.This way of thinking combines some of the best features of mathematics,engineering,and natural science.Like mathematicians,computer scientists use formal languages to denote ideas (specifically computations).Like engineers,they design things, assembling components into systems and evaluating tradeoffs among alternatives. Like scientists,they observe the behavior of complex systems,form hypotheses, and test predictions. The single most important skill for a computer scientist is problem solving. Problem solving means the ability to formulate problems,think creatively about solutions,and express a solution clearly and accurately.As it turns out,the process of learning to program is an excellent opportunity to practice problem- solving skills.That's why this chapter is called,"The way of the program." On one level,you will be learning to program,a useful skill by itself.On another level,you will use programming as a means to an end.As we go along,that end will become clearer. 1.1 The Python programming language The programming language you will be learning is Python.Python is an example of a high-level language;other high-level languages you might have heard of are C,C++,Perl,and Java. As you might infer from the name "high-level language,"there are also low- level languages,sometimes referred to as "machine languages"or "assembly
Chapter 1 The way of the program The goal of this book is to teach you to think like a computer scientist. This way of thinking combines some of the best features of mathematics, engineering, and natural science. Like mathematicians, computer scientists use formal languages to denote ideas (specifically computations). Like engineers, they design things, assembling components into systems and evaluating tradeoffs among alternatives. Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions. The single most important skill for a computer scientist is problem solving. Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution clearly and accurately. As it turns out, the process of learning to program is an excellent opportunity to practice problemsolving skills. That’s why this chapter is called, “The way of the program.” On one level, you will be learning to program, a useful skill by itself. On another level, you will use programming as a means to an end. As we go along, that end will become clearer. 1.1 The Python programming language The programming language you will be learning is Python. Python is an example of a high-level language; other high-level languages you might have heard of are C, C++, Perl, and Java. As you might infer from the name “high-level language,” there are also lowlevel languages, sometimes referred to as “machine languages” or “assembly
The way of the program languages."Loosely speaking,computers can only execute programs written in low-level languages.Thus,programs written in a high-level language have to be processed before they can run.This extra processing takes some time,which is a small disadvantage of high-level languages. But the advantages are enormous.First,it is much easier to program in a high- level language.Programs written in a high-level language take less time to write, they are shorter and easier to read,and they are more likely to be correct.Second, high-level languages are portable,meaning that they can run on different kinds of computers with few or no modifications.Low-level programs can run on only one kind of computer and have to be rewritten to run on another. Due to these advantages,almost all programs are written in high-level languages. Low-level languages are used only for a few specialized applications. Two kinds of programs process high-level languages into low-level languages:in- terpreters and compilers.An interpreter reads a high-level program and exe- cutes it,meaning that it does what the program says.It processes the program a little at a time,alternately reading lines and performing computations. SOURCE INTERPRETER OUTPUT CODE A compiler reads the program and translates it completely before the program starts running.In this case,the high-level program is called the source code, and the translated program is called the object code or the executable.Once a program is compiled,you can execute it repeatedly without further translation. SOURCE COMPILER OBJECT EXECUTOR OUTPUT CODE CODE Python is considered an interpreted language because Python programs are exe- cuted by an interpreter.There are two ways to use the interpreter:command-line mode and script mode.In command-line mode,you type Python programs and the interpreter prints the result:
2 The way of the program languages.” Loosely speaking, computers can only execute programs written in low-level languages. Thus, programs written in a high-level language have to be processed before they can run. This extra processing takes some time, which is a small disadvantage of high-level languages. But the advantages are enormous. First, it is much easier to program in a highlevel language. Programs written in a high-level language take less time to write, they are shorter and easier to read, and they are more likely to be correct. Second, high-level languages are portable, meaning that they can run on different kinds of computers with few or no modifications. Low-level programs can run on only one kind of computer and have to be rewritten to run on another. Due to these advantages, almost all programs are written in high-level languages. Low-level languages are used only for a few specialized applications. Two kinds of programs process high-level languages into low-level languages: interpreters and compilers. An interpreter reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations. SOURCE OUTPUT CODE INTERPRETER A compiler reads the program and translates it completely before the program starts running. In this case, the high-level program is called the source code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further translation. OUTPUT CODE OBJECT EXECUTOR CODE SOURCE COMPILER Python is considered an interpreted language because Python programs are executed by an interpreter. There are two ways to use the interpreter: command-line mode and script mode. In command-line mode, you type Python programs and the interpreter prints the result:
1.2 What is a program? 3 python Python2.4.1(#1,Apr292005,00:28:56) Type "help","copyright","credits"or "license"for more information. >>print 1+1 2 The first line of this example is the command that starts the Python interpreter. The next two lines are messages from the interpreter.The third line starts with >>>which is the prompt the interpreter uses to indicate that it is ready.We typed print 11,and the interpreter replied 2. Alternatively,you can write a program in a file and use the interpreter to execute the contents of the file.Such a file is called a script.For example,we used a text editor to create a file named latoya.py with the following contents: print 1 +1 By convention,files that contain Python programs have names that end with.py. To execute the program,we have to tell the interpreter the name of the script: python latoya.py 2 In other development environments,the details of executing programs may differ. Also,most programs are more interesting than this one. Most of the examples in this book are executed on the command line.Working on the command line is convenient for program development and testing,because you can type programs and execute them immediately.Once you have a working program,you should store it in a script so you can execute or modify it in the future. 1.2 What is a program? A program is a sequence of instructions that specifies how to perform a com- putation.The computation might be something mathematical,such as solving a system of equations or finding the roots of a polynomial,but it can also be a symbolic computation,such as searching and replacing text in a document or (strangely enough)compiling a program. The details look different in different languages,but a few basic instructions appear in just about every language: input:Get data from the keyboard,a file,or some other device
1.2 What is a program? 3 $ python Python 2.4.1 (#1, Apr 29 2005, 00:28:56) Type "help", "copyright", "credits" or "license" for more information. >>> print 1 + 1 2 The first line of this example is the command that starts the Python interpreter. The next two lines are messages from the interpreter. The third line starts with >>>, which is the prompt the interpreter uses to indicate that it is ready. We typed print 1 + 1, and the interpreter replied 2. Alternatively, you can write a program in a file and use the interpreter to execute the contents of the file. Such a file is called a script. For example, we used a text editor to create a file named latoya.py with the following contents: print 1 + 1 By convention, files that contain Python programs have names that end with .py. To execute the program, we have to tell the interpreter the name of the script: $ python latoya.py 2 In other development environments, the details of executing programs may differ. Also, most programs are more interesting than this one. Most of the examples in this book are executed on the command line. Working on the command line is convenient for program development and testing, because you can type programs and execute them immediately. Once you have a working program, you should store it in a script so you can execute or modify it in the future. 1.2 What is a program? A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or (strangely enough) compiling a program. The details look different in different languages, but a few basic instructions appear in just about every language: input: Get data from the keyboard, a file, or some other device
4 The way of the program output:Display data on the screen or send data to a file or other device. math:Perform basic mathematical operations like addition and multiplication. conditional execution:Check for certain conditions and execute the appropri- ate sequence of statements. repetition:Perform some action repeatedly,usually with some variation. Believe it or not,that's pretty much all there is to it.Every program you've ever used,no matter how complicated,is made up of instructions that look more or less like these.Thus,we can describe programming as the process of breaking a large,complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions. That may be a little vague,but we will come back to this topic later when we talk about algorithms. 1.3 What is debugging? Programming is a complex process,and because it is done by human beings,it often leads to errors.For whimsical reasons,programming errors are called bugs and the process of tracking them down and correcting them is called debugging. Three kinds of errors can occur in a program:syntax errors,runtime errors,and semantic errors.It is useful to distinguish between them in order to track them down more quickly. 1.3.1 Syntax errors Python can only execute a program if the program is syntactically correct;oth- erwise,the process fails and returns an error message.Syntax refers to the structure of a program and the rules about that structure.For example,in En- glish,a sentence must begin with a capital letter and end with a period.this sentence contains a syntax error.So does this one For most readers,a few syntax errors are not a significant problem,which is why we can read the poetry of e.e.cummings without spewing error messages.Python is not so forgiving.If there is a single syntax error anywhere in your program, Python will print an error message and quit,and you will not be able to run your program.During the first few weeks of your programming career,you will probably spend a lot of time tracking down syntax errors.As you gain experience, though,you will make fewer errors and find them faster
4 The way of the program output: Display data on the screen or send data to a file or other device. math: Perform basic mathematical operations like addition and multiplication. conditional execution: Check for certain conditions and execute the appropriate sequence of statements. repetition: Perform some action repeatedly, usually with some variation. Believe it or not, that’s pretty much all there is to it. Every program you’ve ever used, no matter how complicated, is made up of instructions that look more or less like these. Thus, we can describe programming as the process of breaking a large, complex task into smaller and smaller subtasks until the subtasks are simple enough to be performed with one of these basic instructions. That may be a little vague, but we will come back to this topic later when we talk about algorithms. 1.3 What is debugging? Programming is a complex process, and because it is done by human beings, it often leads to errors. For whimsical reasons, programming errors are called bugs and the process of tracking them down and correcting them is called debugging. Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors. It is useful to distinguish between them in order to track them down more quickly. 1.3.1 Syntax errors Python can only execute a program if the program is syntactically correct; otherwise, the process fails and returns an error message. Syntax refers to the structure of a program and the rules about that structure. For example, in English, a sentence must begin with a capital letter and end with a period. this sentence contains a syntax error. So does this one For most readers, a few syntax errors are not a significant problem, which is why we can read the poetry of e. e. cummings without spewing error messages. Python is not so forgiving. If there is a single syntax error anywhere in your program, Python will print an error message and quit, and you will not be able to run your program. During the first few weeks of your programming career, you will probably spend a lot of time tracking down syntax errors. As you gain experience, though, you will make fewer errors and find them faster