1.4.HARDWARE BASICS Output Devices CPL Input Devices Main Memory Secondary Memory Figure 1.1:Functional View of a Computer. analysis.For most problems,the bottom-line is whether a working,reliable system can be built.Often we require empirical testing of the system to determine that this bottom-line has been met.As you begin writing your own programs,you will get plenty of opportunities to observe your solutions in action. 1.4 Hardware Basics You don't have to know all the details of how a computer works to be a successful programmer,but under- standing 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 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. 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.4. HARDWARE BASICS 3 Input Devices CPU Secondary Memory Main Memory Output Devices Figure 1.1: Functional View of a Computer. analysis. For most problems, the bottom-line is whether a working, reliable system can be built. Often we require empirical testing of the system to determine that this bottom-line has been met. As you begin writing your own programs, you will get plenty of opportunities to observe your solutions in action. 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 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. 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
4 CHAPTER 1.COMPUTERS AND PROGRAMS 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.("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 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 computa- tions 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 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 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 compiling process.The high-level program is called source code,and the resulting 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 instruction by instruction as necessary.Figure 1.3 illustrates the process The difference between interpreting and compiling is that 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 languages have over machine lan- guage:portability.The machine language of a computer is created by the designers of the particular CPU
4 CHAPTER 1. COMPUTERS AND PROGRAMS 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. (“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 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, unambiguoussyntax 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 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 represented in binary notation (as sequences of 0s 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 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 compiling process. The high-level program is called source code, and the resulting 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 instruction by instruction as necessary. Figure 1.3 illustrates the process. The difference between interpreting and compiling is that 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 languages have over machine language: portability. The machine language of a computer is created by the designers of the particular CPU
1.6.THE MAGIC OF PYTHON 5 Source Code Compiler Machine (Program) Code Running Inputs Program Outputs Figure 1.2:Compiling a High-Level Language Source Code Computer (Program) Running an Outputs Interpreter Inputs Figure 1.3:Interpreting a High-Level Language. Each kind of computer has its own machine language.A program for a Pentium CPU won't run on a Mac- intosh 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.1(#1,Jun212001,11:39:00) [GCC pgcc-2.91.66 19990314 (egcs-1.1.2 release)]on linux2 Type "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
1.6. THE MAGIC OF PYTHON 5 (Program) Compiler Machine Code Running Inputs Outputs Source Code Program Figure 1.2: Compiling a High-Level Language Code Computer Inputs Outputs Source (Program) Running an Interpreter Figure 1.3: Interpreting a High-Level Language. Each kind of computer 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: Python 2.1 (#1, Jun 21 2001, 11:39:00) [GCC pgcc-2.91.66 19990314 (egcs-1.1.2 release)] on linux2 Type "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
6 CHAPTER 1.COMPUTERS AND PROGRAMS >>print "Hello,World" Hello,World >>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 interactive session is being illustrated.It's a good idea to fire up Python and try the examples for 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 fiction.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. >>>he11o() Hello Computers are Fun >>> Do you see what this does?The two print statements from the hello function are executed in sequence. You may be wondering about the parentheses in the definition and use of hello.Commands can have changeable parts called parameters that are placed within the parentheses.Let's look at an example of a customized greeting using a parameter.First the definition: >>def greet(person): print "Hello",person print "How are you?" Now we can use our customized greeting. >>greet ("John") Hello John How are you? >>greet ("Emily") Hello Emily How are you? >>>
6 CHAPTER 1. COMPUTERS AND PROGRAMS >>> print "Hello, World" Hello, World >>> 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 interactive session is being illustrated. It’s a good idea to fire up Python and try the examples for 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. >>> hello() Hello Computers are Fun >>> Do you see what this does? The two print statements from the hello function are executed in sequence. You may be wondering about the parentheses in the definition and use of hello. Commands can have changeable parts called parameters that are placed within the parentheses. Let’s look at an example of a customized greeting using a parameter. First the definition: >>> def greet(person): print "Hello", person print "How are you?" Now we can use our customized greeting. >>> greet("John") Hello John How are you? >>> greet("Emily") Hello Emily How are you? >>>
1.6.THE MAGIC OF PYTHON 7 Can you see what is happening here?When we use greet we can send different names to customize the result.We will discuss parameters in detail later on.For the time being,our functions will not use parameters, so the parentheses will be empty,but you still need to include them when defining and using functions. One problem with entering functions interactively at the Python prompt like this is that the definitions go away when we quit Python.If we want to use them again the next time,we have to type them all over again. Programs are usually created by typing definitions into a separate file called a module or script.This file is saved on a disk so that it can be used over and over again. A module file is just a text file,and you can create one using any program for editing text,like a notepad or word processor program(provided you save your program as a"plain text"file).A special type of program known as a programming environment simplifies the process.A programming environment is specifically designed to help programmers write programs and includes features such as automatic indenting,color high- lighting,and interactive development.The standard Python distribution includes a programming environment called Idle that you may use for working on the programs in this book. Let's illustrate the use of a module file by writing and running a complete program.Our program will illustrate a mathematical concept known as chaos.Here is the program as we would type it into Idle or some other editor and save in a module file: File:chaos.py A simple program illustrating chaotic behavior. def main(): print "This program illustrates a chaotic function" x input("Enter a number between 0 and 1:" for i in range(10): x=3.9*x*(1-x) print x main() This file should be saved with with the name chaos.py.The.py extension indicates that this is a Python module.You can see that this particular example contains lines to define a new function called main. (Programs are often placed in a function called main.The last line of the file is the command to invoke this function.Don't worry if you don't understand what main actually does;we will discuss it in the next section.The point here is that once we have a program in a module file,we can run it any time we want. This program can be run in a number of different ways that depend on the actual operating system and programming environment that you are using.If you are using a windowing system,you can run a Python program by (double-)clicking on the module file's icon.In a command-line situation,you might type a command like python chaos.py.If you are using Idle (or another programming environment)you can run a program by opening it in the editor and then selecting a command like import,run,or execute. One method that should always work is to start the Python interpreter and then import the file.Here is how that looks >>import chaos This program illustrates a chaotic function Enter a number between 0 and 1:.25 0.73125 0.76644140625 0.698135010439 0.82189581879 0.570894019197 0.955398748364 0.166186721954 0.540417912062 0.9686289303 0.118509010176 >>>
1.6. THE MAGIC OF PYTHON 7 Can you see what is happening here? When we use greet we can send different names to customize the result. We will discuss parameters in detail later on. For the time being, our functions will not use parameters, so the parentheses will be empty, but you still need to include them when defining and using functions. One problem with entering functions interactively at the Python prompt like this is that the definitions go away when we quit Python. If we want to use them again the next time, we have to type them all over again. Programs are usually created by typing definitions into a separate file called a module or script. This file is saved on a disk so that it can be used over and over again. A module file is just a text file, and you can create one using any program for editing text, like a notepad or word processor program (provided you save your program as a “plain text” file). A special type of program known as a programming environment simplifies the process. A programming environment is specifically designed to help programmers write programs and includes features such as automatic indenting, color highlighting, and interactive development. The standard Python distribution includes a programming environment called Idle that you may use for working on the programs in this book. Let’s illustrate the use of a module file by writing and running a complete program. Our program will illustrate a mathematical concept known as chaos. Here is the program as we would type it into Idle or some other editor and save in a module file: # File: chaos.py # A simple program illustrating chaotic behavior. def main(): print "This program illustrates a chaotic function" x = input("Enter a number between 0 and 1: ") for i in range(10): x = 3.9 * x * (1 - x) print x main() This file should be saved with with the name chaos.py. The .py extension indicates that this is a Python module. You can see that this particular example contains lines to define a new function called main. (Programs are often placed in a function called main.) The last line of the file is the command to invoke this function. Don’t worry if you don’t understand what main actually does; we will discuss it in the next section. The point here is that once we have a program in a module file, we can run it any time we want. This program can be run in a number of different ways that depend on the actual operating system and programming environment that you are using. If you are using a windowing system, you can run a Python program by (double-)clicking on the module file’s icon. In a command-line situation, you might type a command like python chaos.py. If you are using Idle (or another programming environment) you can run a program by opening it in the editor and then selecting a command like import, run, or execute. One method that should always work is to start the Python interpreter and then import the file. Here is how that looks. >>> import chaos This program illustrates a chaotic function Enter a number between 0 and 1: .25 0.73125 0.76644140625 0.698135010439 0.82189581879 0.570894019197 0.955398748364 0.166186721954 0.540417912062 0.9686289303 0.118509010176 >>>