6 Chapter 1.Computers and Programs turned off,the information in the memory is lost.Thus,there must also be some secondary memory that provides more permanent storage.In a modern per- sonal computer,this is usually some sort of magnetic medium such as a hard disk(also called a hard drive)or floppy.Optical media such as CD(compact disc)and DVD(digital versatile disc)are also common. Humans interact with the computer through input and output devices.You are probably familiar with common devices such as a keyboard,mouse,and monitor(video screen).Information from input devices is processed by the CPU and may be shuffled off to the main or secondary memory.Similarly,when infor- mation needs to be displayed,the CPU sends it to one or more output devices. So what happens when you fire up your favorite game or word processing program?First,the instructions that comprise the program are copied from the (more)permanent secondary memory into the main memory of the computer. Once the instructions are loaded,the CPU starts executing the program. Technically the CPU follows a process called the fetch-execute cycle.The first instruction is retrieved from memory,decoded to figure out what it represents, and the appropriate action carried out.Then the next instruction is fetched, decoded and executed.The cycle continues,instruction after instruction.This is really all the computer does from the time that you turn it on until you turn it off again:fetch,decode,execute.It doesn't seem very exciting,does it?But the computer can execute this stream of simple instructions with blazing speed, zipping through millions of instructions each second.Put enough simple instruc- tions together in just the right way,and the computer does amazing things. 1.5 Programming Languages Remember that a program is just a sequence of instructions telling a computer what to do.Obviously,we need to provide those instructions in a language that a computer can understand.It would be nice if we could just tell a computer what to do using our native language,like they do in science fiction movies.("Com- puter,how long will it take to reach planet Alphalpha at maximum warp?")Un- fortunately,despite the continuing efforts of many top-flight computer scientists (including your author),designing a computer to understand human language is still an unsolved problem. Even if computers could understand us,human languages are not very well suited for describing complex algorithms.Natural language is fraught with am- biguity and imprecision.For example,if I say:"I saw the man in the park with the telescope,"did I have the telescope,or did the man?And who was in the
Chapter 1. Computers and Programs turned off, the information in the memory is lost. Thus, there must also be some secondary memory that provides more permanent storage. In a modern personal computer, this is usually some sort of magnetic medium such as a hard disk (also called a hard drive) or floppy. Optical media such as CD (compact disc) and DVD (digital versatile disc) are also common. Humans interact with the computer through input and output devices. You are probably familiar with common devices such as a keyboard, mouse, and monitor (video screen). Information from input devices is processed by the CPU and may be shuffled off to the main or secondary memory. Similarly, when information needs to be displayed, the CPU sends it to one or more output devices. So what happens when you fire up your favorite game or word processing program? First, the instructions that comprise the program are copied from the (more) permanent secondary memory into the main memory of the computer. Once the instructions are loaded, the CPU starts executing the program. Technically the CPU follows a process called the fetch-execute cycle. The first instruction is retrieved from memory, decoded to figure out what it represents, and the appropriate action carried out. Then the next instruction is fetched, decoded and executed. The cycle continues, instruction after instruction. This is really all the computer does from the time that you turn it on until you turn it off again: fetch, decode, execute. It doesn't seem very exciting, does it? But the computer can execute this stream of simple instructions with blazing speed, zipping through millions of instructions each second. Put enough simple instructions together in just the right way, and the computer does amazing things. 1.5 1 Programming Languages Remember that a program is just a sequence of instructions telling a computer what to do. Obviously, we need to provide those instructions in a language that a computer can understand. It would be nice if we could just tell a computer what to do using our native language, like they do in science fiction movies. ("Computer, how long will it take to reach planet Alphalpha at maximum warp?") Unfortunately, despite the continuing efforts of many top-flight computer scientists (including your author), designing a computer to understand human language is still an unsolved problem. Even if computers could understand us, human languages are not very well suited for describing complex algorithms. Natural language is fraught with ambiguity and imprecision. For example, if I say: "I saw the man in the park with the telescope," did I have the telescope, or did the man? And who was in the
1.5.Programming Languages 7 park?We understand each other most of the time only because all humans share a vast store of common knowledge and experience.Even then,miscommunica- tion is commonplace. Computer scientists have gotten around this problem by designing notations for expressing computations in an exact and unambiguous way.These special notations are called programming languages.Every structure in a programming language has a precise form (its syntax)and a precise meaning(its semantics). A programming language is something like a code for writing down the instruc- tions that a computer will follow.In fact,programmers often refer to their programs as computer code,and the process of writing an algorithm in a pro- gramming language is called coding. Python is one example of a programming language.It is the language that we will use throughout this book.You may have heard of some other languages, such as C++,Java,Perl,Scheme,or BASIC.Although these languages differ in many details,they all share the property of having well-defined,unambiguous syntax and semantics. All of the languages mentioned above are examples of high-level computer languages.Although they are precise,they are designed to be used and under- stood by humans.Strictly speaking,computer hardware can only understand a very low-level language known as machine language. Suppose we want the computer to add two numbers.The instructions that the CPU actually carries out might be something like this. load the number from memory location 2001 into the CPU load the number from memory location 2002 into the CPU Add the two numbers in the CPU store the result into location 2003 This seems like a lot of work to add two numbers,doesn't it?Actually,it's even more complicated than this because the instructions and numbers are repre- sented in binary notation (as sequences of Os and 1s). In a high-level language like Python,the addition of two numbers can be expressed more naturally:c =a b.That's a lot easier for us to understand, but we need some way to translate the high-level language into the machine language that the computer can execute.There are two ways to do this:a high-level language can either be compiled or interpreted. A compiler is a complex computer program that takes another program writ- ten in a high-level language and translates it into an equivalent program in the machine language of some computer.Figure 1.2 shows a block diagram of the
1.5. Programming Languages park? We understand each other most of the time only because all humans share a vast store of common knowledge and experience. Even then, miscommunication is commonplace. Computer scientists have gotten around this problem by designing notations for expressing computations in an exact and unambiguous way. These special notations are called programming languages. Every structure in a programming language has a precise form (its syntax) and a precise meaning (its semantics). A programming language is something like a code for writing down the instructions that a computer will follow. In fact, programmers often refer to their programs as computer code, and the process of writing an algorithm in a programming language is called coding. Python is one example of a programming language. It is the language that we will use throughout this book. You may have heard of some other languages, such as C++, Java, Perl, Scheme, or BASIC. Although these languages differ in many details, they all share the property of having well-defined, unambiguous syntax and semantics. All of the languages mentioned above are examples of high-level computer languages. Although they are precise, they are designed to be used and understood by humans. Strictly speaking, computer hardware can only understand a very low-level language known as machine language. Suppose we want the computer to add two numbers. The instructions that the CPU actually carries out might be something like this. load the number from memory location 2001 into the CPU load the number from memory location 2002 into the CPU Add the two numbers in the CPU store the result into location 2003 This seems like a lot of work to add two numbers, doesn't it? Actually, it's even more compHcated than this because the instructions and numbers are represented in binary notation (as sequences of Os and Is). In a high-level language like Python, the addition of two numbers can be expressed more naturally: c = a + b. That's a lot easier for us to understand, but we need some way to translate the high-level language into the machine language that the computer can execute. There are two ways to do this: a high-level language can either be compiled or interpreted. A compiler is a complex computer program that takes another program written in a high-level language and translates it into an equivalent program in the machine language of some computer. Figure 1.2 shows a block diagram of the
8 Chapter 1.Computers and Programs Source Code Compiler Machine (Program) Code Inputs Running Program Outputs Figure 1.2:Compiling a High-Level Language Source Code (Program) Computer Running an Outputs Interpreter Inputs Figure 1.3:Interpreting a High-Level Language. compiling process.The high-level program is called source code,and the re- sulting machine code is a program that the computer can directly execute.The dashed line in the diagram represents the execution of the machine code. An interpreter is a program that simulates a computer that understands a high-level language.Rather than translating the source program into a machine language equivalent,the interpreter analyzes and executes the source code in- struction by instruction as necessary.Figure 1.3 illustrates the process. The difference between interpreting and compiling is compiling is a one- shot translation;once a program is compiled,it may be run over and over again without further need for the compiler or the source code.In the interpreted case,the interpreter and the source are needed every time the program runs. Compiled programs tend to be faster,since the translation is done once and for all,but interpreted languages lend themselves to a more flexible programming environment as programs can be developed and run interactively. The translation process highlights another advantage that high-level lan- guages have over machine language:portability.The machine language of a computer is created by the designers of the particular CPU.Each kind of com-
Chapter 1. Computers and Programs Figure 1.2: Compiling a High-Level Language Computer Running an Interpreter Outputs Figure 1.3: Interpreting a High-Level Language. compiling process. The high-level program is called source code, and the re- sulting machine code is a program that the computer can directly execute. The dashed line in the diagram represents the execution of the machine code. An interpreter is a program that simulates a computer that understands a high-level language. Rather than translating the source program into a machine language equivalent, the interpreter analyzes and executes the source code in- struction by instruction as necessary. Figure 1.3 illustrates the process. The difference between interpreting and compiling is compiling is a oneshot translation; once a program is compiled, it may be run over and over again without further need for the compiler or the source code. In the interpreted case, the interpreter and the source are needed every time the program runs. Compiled programs tend to be faster, since the translation is done once and for all, but interpreted languages lend themselves to a more flexible programming environment as programs can be developed and run interactively. The translation process highlights another advantage that high-level languages have over machine language: portability. The machine language of a computer is created by the designers of the particular CPU. Each kind of com-
1.6.The Magic of Python 9 puter has its own machine language.A program for a Pentium CPU won't run on a Macintosh that sports a PowerPC.On the other hand,a program written in a high-level language can be run on many different kinds of computers as long as there is a suitable compiler or interpreter (which is just another program).For example,if I design a new computer,I can also program a Python interpreter for it,and then any program written in Python can be run on my new computer,as is. 1.6 The Magic of Python Now that you have all the technical details,it's time to start having fun with Python.The ultimate goal is to make the computer do our bidding.To this end,we will write programs that control the computational processes inside the machine.You have already seen that there is no magic in this process,but in some ways programming feels like magic. The computational processes inside the computer are like magical spirits that we can harness for our work.Unfortunately,those spirits only understand a very arcane language that we do not know.What we need is a friendly Genie that can direct the spirits to fulfill our wishes.Our Genie is a Python interpreter.We can give instructions to the Python interpreter,and it directs the underlying spirits to carry out our demands.We communicate with the Genie through a special language of spells and incantations(i.e.,Python).The best way to start learning about Python is to let our Genie out of the bottle and try some spells. You can start the Python interpreter in an interactive mode and type in some commands to see what happens.When you first start the interpreter program, you may see something like the following: Python2.3(#1,Mar132003,11:26:03) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)]on linux2 Type "help","copyright","credits"or "license"for more information. >>> The >>>is a Python prompt indicating that the Genie is waiting for us to give it a command.In programming languages,a complete command is called a statement. Here is a sample interaction with the Python interpreter: >>print "Hello,World" Hello,World
1.6. The Magic of Python puter has its own machine language. A program for a Pentium CPU won't run on a Macintosh that sports a PowerPC. On the other hand, a program written in a high-level language can be run on many different kinds of computers as long as there is a suitable compiler or interpreter (which is just another program) . For example, if I design a new computer, I can also program a Python interpreter for it, and then any program written in Python can be run on my new computer, as is. 1.6| The Magic of Python Now that you have all the technical details, it's time to start having fun with Python. The ultimate goal is to make the computer do our bidding. To this end, we will write programs that control the computational processes inside the machine. You have already seen that there is no magic in this process, but in some ways programming /eeZs like magic. The computational processes inside the computer are like magical spirits that we can harness for our work. Unfortunately, those spirits only understand a very arcane language that we do not know. What we need is a friendly Genie that can direct the spirits to fulfill our wishes. Our Genie is a Python interpreter. We can give instructions to the Python interpreter, and it directs the underlying spirits to carry out our demands. We communicate with the Genie through a special language of spells and incantations (i.e.. Python). The best way to start learning about Python is to let our Genie out of the bottle and try some spells. You can start the Python interpreter in an interactive mode and type in some commands to see what happens. When you first start the interpreter program, you may see something like the following: Python 2.3 (#1, Mar 13 2003, 11:26:03) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "help", "copyright", "credits" or "license" for more information >» The >>> is a Python prompt indicating that the Genie is waiting for us to give it a command. In programming languages, a complete command is called a statement. Here is a sample interaction with the Python interpreter: >» print "Hello, World" Hello, World
10 Chapter 1.Computers and Programs >>print 2 +3 5 >print"2+3=",2+3 2+3=5 Here I have tried out three examples using the Python print statement.The first statement asks Python to display the literal phrase Hello,World.Python responds on the next line by printing the phrase.The second print statement asks Python to print the sum of 2 and 3.The third print combines these two ideas.Python prints the part in quotes"2+3="followed by the result of adding 2 +3,which is 5. This kind of interaction is a great way to try out new things in Python.Snip- pets of interactive sessions are sprinkled throughout this book.When you see the Python prompt>>>in an example,that should tip you off that an inter- active session is being illustrated.It's a good idea to fire up Python and try the examples yourself. Usually we want to move beyond snippets and execute an entire sequence of statements.Python lets us put a sequence of statements together to create a brand-new command called a function.Here is an example of creating a new function called hello: >>def hello(): print "Hello" print "Computers are Fun" >>> The first line tells Python that we are defining a new function called hello.The following lines are indented to show that they are part of the hello function. The blank line (obtained by hitting the <Enter>key twice)lets Python know that the definition is finished,and the interpreter responds with another prompt.No- tice that the definition did not cause anything to happen.We have told Python what should happen when the hello function is used as a command;we haven't actually asked Python to perform it yet. A function is invoked by typing its name.Here's what happens when we use our hello command: >he11o() Hello Computers are Fun >>>
10 Chapter 1. Computers and Programs >» print 2 + 3 5 >» print "2 + 3 =", 2 + 3 2 + 3 = 5 Here I have tried out three examples using the Python print statement. The first statement asks Python to display the literal phrase Hello, World. Python responds on the next line by printing the phrase. The second print statement asks Python to print the sum of 2 and 3. The third print combines these two ideas. Python prints the part in quotes "2 + 3 =" followed by the result of adding 2 + 3, which is 5. This kind of interaction is a great way to try out new things in Python. Snippets of interactive sessions are sprinkled throughout this book. When you see the Python prompt > > > in an example, that should tip you off that an inter- active session is being illustrated. It's a good idea to fire up Python and try the examples yourself. Usually we want to move beyond snippets and execute an entire sequence of statements. Python lets us put a sequence of statements together to create a brand-new command called a function. Here is an example of creating a new function called hello: >» def hello : print "Hello" print "Computers are Fun" >» The first line tells Python that we are defining a new function called hello. The following lines are indented to show that they are part of the hello function. The blank line (obtained by hitting the <Enter> key twice) lets Python know that the definition is finished, and the interpreter responds with another prompt. Notice that the definition did not cause anything to happen. We have told Python what should happen when the hello function is used as a command; we haven't actually asked Python to perform it yet. A function is invoked by typing its name. Here's what happens when we use our hello command: >» helloO Hello Computers are Fun >>>