1.4.Hardware Basics 5 Output CPU Devices Input Devices Main Secondary Memory Memory Figure 1.1:Functional View of a Computer. tional science (using powerful computers to model scientific data),databases, software engineering,web and multimedia design,management information systems,and computer security.Wherever computing is done,the skills and knowledge of computer science are being applied. 1.4 Hardware Basics You don't have to know all the details of how a computer works to be a successful programmer,but understanding the underlying principles will help you master the steps we go through to put our programs into action.It's a bit like driving a car.Knowing a little about internal combustion engines helps to explain why you have to do things like fill the gas tank,start the engine,step on the accelerator, etc.You could learn to drive by just memorizing what to do,but a little more knowledge makes the whole process much more understandable.Let's take a moment to"look under the hood"of your computer. Although different computers can vary significantly in specific details,at a higher level all modern digital computers are remarkably similar.Figure 1.1 shows a functional view of a computer.The central processing unit (CPU)is the "brain"of the machine.This is where all the basic operations of the computer are carried out.The CPU can perform simple arithmetic operations like adding two numbers and can also do logical operations like testing to see if two numbers are equal The memory stores programs and data.The CPU can only directly access information that is stored in main memory (called RAM for Random Access Mem- ory).Main memory is fast,but it is also volatile.That is,when the power is
1.4. Hardware Basics Output CPU Devices Input Devices Secondary Memory Main Memory Figure 1.1: Functional View of a Computer. tional science (using powerful computers to model scientific data), databases, software engineering, web and multimedia design, management information systems, and computer security. Wherever computing is done, the skills and knowledge of computer science are being applied. 1.4 Hardware Basics You don't have to know all the details of how a computer works to be a successful programmer, but understanding the underlying principles will help you master the steps we go through to put our programs into action. It's a bit like driving a car. Knowing a little about internal combustion engines helps to explain why you have to do things like fill the gas tank, start the engine, step on the accelerator, etc. You could learn to drive by just memorizing what to do, but a little more knowledge makes the whole process much more understandable. Let's take a moment to "look under the hood" of your computer. Although different computers can vary significantly in specific details, at a higher level all modern digital computers are remarkably similar. Figure 1.1 shows a functional view of a computer. The central processing unit (CPU) is the "brain" of the machine. This is where all the basic operations of the computer are carried out. The CPU can perform simple arithmetic operations like adding two numbers and can also do logical operations like testing to see if two numbers are equal. The memory stores programs and data. The CPU can only directly access information that is stored in main memory (called RAM for Random Access Memory). Main memory is fast, but it is also volatile. That is, when the power is
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