id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
19,500 | module documentation working with multiple modules widgets example programdice roller building buttons building dice the main program summary exercises data collections example problemsimple statistics applying lists lists and arrays list operations statistics with lists lists of records designing with lists and classes case studypython calculator calculator as an object constructing the interface processing buttons non-sequential collections dictionary basics dictionary operations example programword frequency summary exercises object-oriented design the process of ood case studyracquetball simulation candidate objects and methods implementing simstats implementing rballgame implementing player the complete program case studydice poker program specification identifying candidate objects implementing the model text-based ui developing gui |
19,501 | contents oo concepts encapsulation polymorphism inheritance summary exercises algorithm design and recursion searching simple searching problem strategy linear search strategy binary search comparing algorithms recursive problem-solving recursive definitions recursive functions examplestring reversal exampleanagrams examplefast exponentiation examplebinary search recursion vs iteration sorting algorithms naive sortingselection sort divide and conquermerge sort comparing sorts hard problems towers of hanoi the halting problem conclusion summary exercises |
19,502 | computers and programs objectives to understand the respective roles of hardware and software in computing system to learn what computer scientists study and the techniques that they use to understand the basic design of modern computer to understand the form and function of computer programming languages to begin using the python programming language to learn about chaotic models and their implications for computing the universal machine almost everyone has used computer at one time or another perhaps you have played computer games or used computer to write paper or balance your checkbook computers are used to predict the weatherdesign airplanesmake moviesrun businessesperform financial transactionsand control factories have you ever stopped to wonder what exactly computer ishow can one device perform so many different tasksthese basic questions are the starting point for learning about computers and computer programming modern computer can be defined as " machine that stores and manipulates information under the control of changeable program there are two key elements to this definition the first is that computers are devices for manipulating information this means we can put information into computerand it can transform the information into newuseful formsand then output or display the information for our interpretation computers are not the only machines that manipulate information when you use simple calculator to add up column of numbersyou are entering information (the numbersand the |
19,503 | computers and programs calculator is processing the information to compute running sum which is then displayed another simple example is gas pump as you fill your tankthe pump uses certain inputsthe current price of gas per gallon and signals from sensor that reads the rate of gas flowing into your car the pump transforms this input into information about how much gas you took and how much money you owe we would not consider either the calculator or the gas pump as full-fledged computersalthough modern versions of these devices may actually contain embedded computers they are different from computers in that they are built to perform singlespecific task this is where the second part of our definition comes into the picturecomputers operate under the control of changeable program what exactly does this meana computer program is detailedstep-by-step set of instructions telling computer exactly what to do if we change the programthen the computer performs different sequence of actionsand henceperforms different task it is this flexibility that allows your pc to be at one moment word processorat the next moment financial plannerand later onan arcade game the machine stays the samebut the program controlling the machine changes every computer is just machine for executing (carrying outprograms there are many different kinds of computers you might be familiar with macintoshes and pcsbut there are literally thousands of other kinds of computers both real and theoretical one of the remarkable discoveries of computer science is the realization that all of these different computers have the same powerwith suitable programmingeach computer can basically do all the things that any other computer can do in this sensethe pc that you might have sitting on your desk is really universal machine it can do anything you want it to doprovided you can describe the task to be accomplished in sufficient detail now that' powerful machine program power you have already learned an important lesson of computingsoftware (programsrules the hardware (the physical machineit is the software that determines what any computer can do without softwarecomputers would just be expensive paperweights the process of creating software is called programmingand that is the main focus of this book computer programming is challenging activity good programming requires an ability to see the big picture while paying attention to minute detail not everyone has the talent to become first-class programmerjust as not everyone has the skills to be professional athlete howevervirtually anyone can learn how to program computers with some patience and effort on your partthis book will help you to become programmer there are lots of good reasons to learn programming programming is fundamental part of computer science and isthereforeimportant to anyone interested in becoming computer professional but others can also benefit from the experience computers have become commonplace tool in our society understanding the strengths and limitations of this tool requires an understanding of programming non-programmers often feel they are slaves of their computers programmershoweverare truly in control if you want to become more intelligent user of computersthen this book is for you |
19,504 | programming can also be loads of fun it is an intellectually engaging activity that allows people to express themselves through useful and sometimes remarkably beautiful creations believe it or notmany people actually write computer programs as hobby programming also develops valuable problem-solving skillsespecially the ability to analyze complex systems by reducing them to interactions of understandable subsystems as you probably knowprogrammers are in great demand more than few liberal arts majors have turned couple of computer programming classes into lucrative career option computers are so commonplace in the business world today that the ability to understand and program computers might just give you the edge over your competitionregardless of your occupation what is computer scienceyou might be surprised to learn that computer science is not the study of computers famous computer scientist named edsger dijkstra once quipped that computers are to computer science what telescopes are to astronomy the computer is an important tool in computer sciencebut it is not itself the object of study since computer can carry out any process that we can describethe real question is what processes can we describeput another waythe fundamental question of computer science is simply what can be computedcomputer scientists use numerous techniques of investigation to answer this question the three main ones are designanalysisand experimentation one way to demonstrate that particular problem can be solved is to actually design solution that iswe develop step-by-step process for achieving the desired result computer scientists call this an algorithm that' fancy word that basically means "recipe the design of algorithms is one of the most important facets of computer science in this book you will find techniques for designing and implementing algorithms one weakness of design is that it can only answer the question what is computablein the positive if can devise an algorithmthen the problem is solvable howeverfailing to find an algorithm does not mean that problem is unsolvable it may mean that ' just not smart enoughor haven' hit upon the right idea yet this is where analysis comes in analysis is the process of examining algorithms and problems mathematically computer scientists have shown that some seemingly simple problems are not solvable by any algorithm other problems are intractable the algorithms that solve these problems take too long or require too much memory to be of practical value analysis of algorithms is an important part of computer sciencethroughout this book we will touch on some of the fundamental principles has examples of unsolvable and intractable problems some problems are too complex or ill-defined to lend themselves to analysis in such casescomputer scientists rely on experimentationthey actually implement systems and then study the resulting behavior even when theoretical analysis is doneexperimentation is often needed in order to verify and refine the analysis for most problemsthe bottom line is whether workingreliable 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 programsyou will get plenty of opportunities to observe your solutions in action have defined computer science in terms of designinganalyzingand evaluating algorithms |
19,505 | output devices cpu input devices main memory secondary memory figure functional view of computer and this is certainly the core of the academic discipline these dayshowevercomputer scientists are involved in far-flung activitiesall of which fall under the general umbrella of computing some example areas include networkinghuman-computer interactionartificial intelligencecomputational science (using powerful computers to model scientific data)databasessoftware engineeringweb and multimedia designmanagement information systemsand computer security wherever computing is donethe skills and knowledge of computer science are being applied hardware basics you don' have to know all the details of how computer works to be successful programmerbut understanding the underlying principles will help you master the steps we go through to put our programs into action it' bit like driving car knowing little about internal combustion engines helps to explain why you have to do things like fill the gas tankstart the enginestep on the acceleratoretc you could learn to drive by just memorizing what to dobut little more knowledge makes the whole process much more understandable let' take moment to "look under the hoodof your computer although different computers can vary significantly in specific detailsat higher level all modern digital computers are remarkably similar figure shows functional view of computer the central processing unit (cpuis the "brainof 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 memorymain memory is fastbut it is also volatile that iswhen the power is turned offthe information in the memory is lost thusthere must also be some secondary memory that provides more permanent storage in modern personal computerthis is usually some sort of magnetic medium such as hard disk (also called hard driveoptical media such as cd (compact discand dvd (digital versatile discand flash memory devices such as usb memory "sticksare also common humans interact with the computer through input and output devices you are probably familiar with common devices such as keyboardmouseand monitor (video screeninformation from |
19,506 | input devices is processed by the cpu and may be shuffled off to the main or secondary memory similarlywhen information needs to be displayedthe cpu sends it to one or more output devices so what happens when you fire up your favorite game or word processing programfirstthe instructions that comprise the program are copied from the (morepermanent secondary memory into the main memory of the computer once the instructions are loadedthe cpu starts executing the program technically the cpu follows process called the fetch-execute cycle the first instruction is retrieved from memorydecoded to figure out what it representsand the appropriate action carried out then the next instruction is fetcheddecoded and executed the cycle continuesinstruction after instruction this is really all the computer does from the time that you turn it on until you turn it off againfetchdecodeexecute it doesn' seem very excitingdoes itbut the computer can execute this stream of simple instructions with blazing speedzipping through millions of instructions each second put enough simple instructions together in just the right wayand the computer does amazing things programming languages remember that program is just sequence of instructions telling computer what to do obviouslywe need to provide those instructions in language that computer can understand it would be nice if we could just tell computer what to do using our native languagelike they do in science fiction movies ("computerhow long will it take to reach planet alphalpha at maximum warp?"unfortunatelydespite the continuing efforts of many top-flight computer scientists (including your author)designing computer to fully understand human language is still an unsolved problem even if computers could understand ushuman languages are not very well suited for describing complex algorithms natural language is fraught with ambiguity and imprecision for exampleif say" saw the man in the park with the telescope,did have the telescopeor did the manand who was in the parkwe understand each other most of the time only because all humans share vast store of common knowledge and experience even thenmiscommunication 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 programming language has precise form (its syntaxand precise meaning (its semanticsa programming language is something like code for writing down the instructions that computer will follow in factprogrammers often refer to their programs as computer codeand the process of writing an algorithm in programming language is called coding python is one example of programming language it is the language that we will use throughout this book you may have heard of some other languagessuch as ++javaperlschemeor basic although these languages differ in many detailsthey all share the property of having well-definedunambiguous syntax and semantics languages themselves tend to evolve over time specificallythe book was written using python version if you have an earlier version of python installed on your computeryou should upgrade to the latest stable version to try out the examples |
19,507 | source code (programcompiler machine code running inputs program outputs figure compiling high-level language all of the languages mentioned above are examples of high-level computer languages although they are precisethey are designed to be used and understood by humans strictly speakingcomputer 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 into the cpu load the number from memory location into the cpu add the two numbers in the cpu store the result into location this seems like lot of work to add two numbersdoesn' itactuallyit' even more complicated than this because the instructions and numbers are represented in binary notation (as sequences of and sin high-level language like pythonthe addition of two numbers can be expressed more naturallyc that' lot easier for us to understandbut 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 thisa high-level language can either be compiled or interpreted compiler is complex computer program that takes another program written in high-level language and translates it into an equivalent program in the machine language of some computer figure shows block diagram of the compiling process the high-level program is called source codeand the resulting machine code is program that the computer can directly execute the dashed line in the diagram represents the execution of the machine code (aka "running the program"an interpreter is program that simulates computer that understands high-level language rather than translating the source program into machine language equivalentthe interpreter analyzes and executes the source code instruction by instruction as necessary figure illustrates the process the difference between interpreting and compiling is that compiling is one-shot translationonce program is compiledit may be run over and over again without further need for the compiler or the source code in the interpreted casethe interpreter and the source are needed every time |
19,508 | source code (programcomputer running an outputs interpreter inputs figure interpreting high-level language the program runs compiled programs tend to be fastersince the translation is done once and for allbut interpreted languages lend themselves to 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 languageportability the machine language of computer is created by the designers of the particular cpu each kind of computer has its own machine language program for intel core duo won' run directly on different cpu on the other handa program written in high-level language can be run on many different kinds of computers as long as there is suitable compiler or interpreter (which is just another programas resulti can run the exact same python program on my laptop and my pdaeven though they have different cpusthey both sport python interpreter the magic of python now that you have all the technical detailsit' time to start having fun with python the ultimate goal is to make the computer do our bidding to this endwe will write programs that control the computational processes inside the machine you have already seen that there is no magic in this processbut in some ways programming feels like magic the computational processes inside the computer are like magical spirits that we can harness for our work unfortunatelythose spirits only understand very arcane language that we do not know what we need is friendly genie that can direct the spirits to fulfill our wishes our genie is python interpreter we can give instructions to the python interpreterand it directs the underlying spirits to carry out our demands we communicate with the genie through special language of spells and incantations ( pythonthe 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 programyou may see something like the followingpython ( : jan : : [gcc (prerelease(ubuntu - ubuntu )on linux type "help""copyright""creditsor "licensefor more information |
19,509 | computers and programs the is python prompt indicating that our genie (the python interpreteris waiting for us to give it command in programming languagesa complete command is called statement an interactive environment for interacting with an interpreter is called command shell or just shell for short here is sample interaction with python shellprint("helloworld!"helloworldprint( print(" =" here have tried out three examples using the python print statement the first statement asks python to display the literal phrase helloworldpython responds on the next line by printing the phrase the second print statement asks python to print the sum of and the third print combines these two ideas python prints the part in quotes followed by the result of adding which is this kind of shell interaction is 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 examplethat should tip you off that an interactive session is being illustrated it' good idea to fire up your own python shell and try the examples usually we want to move beyond one-line snippets and execute an entire sequence of statements python lets us put sequence of statements together to create brand-new command or function here is an example of creating new function called hellodef hello()print("hello"print("computers are fun!"the first line tells python that we are defining new function and we are naming it hello the following lines are indented to show that they are part of the hello function (notesome shells will print ellipses ["at the beginning of the indented linesthe blank line at the end (obtained by hitting the key twicelets python know that the definition is finishedand the shell responds with another prompt notice that typing the definition did not cause python to print anything yet we have told python what should happen when the hello function is used as commandwe haven' actually asked python to perform it yet function is invoked (or calledby typing its name followed by parentheses here' what happens when we use our hello command |
19,510 | hello(hello computers are fundo you see what this doesthe two print statements from the hello function definition 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 (also called argumentsthat are placed within the parentheses let' look at an example of customized greeting using parameter first the definitiondef greet(person)print("hello"personprint("how are you?"now we can use our customized greeting greet("john"hello john how are yougreet("emily"hello emily how are youcan you see what is happening herewhen using greet we can send different names to customize the result you might also notice that this looks similar to the print statements from before in pythonprint is an example of built-in function when we call the print functionthe parameters in the parentheses tell the function what to print we will discuss parameters in detail later on for the time being the important thing to remember is that the parentheses must be included after the function name whenever we want to execute function this is true even when no parameters given for exampleyou can create blank line of output using print without any parameters print(but if you type just the name of the functionomitting the parenthesesthe function will not actually execute insteadan interactive python session will show some output indicating what function that name refers toas this interaction showsgreet print |
19,511 | computers and programs the funny text " aecis the location (addressin computer memory where the greet function definition happens to be stored if you are trying this out on your own computeryou will almost certainly see different address one problem with entering functions interactively into python shell as we did with the hello and greet examples is that the definitions are lost when we quit the shell if we want to use them again the next timewe have to type them all over again programs are usually created by typing definitions into separate file called module or script this file is saved on disk so that it can be used over and over again module file is just text fileand you can create one using any program for editing textlike notepad or word processor program (provided you save your program as "plain textfilea special type of program known as programming environment simplifies the process programming environment is specifically designed to help programmers write programs and includes features such as automatic indentingcolor highlightingand interactive development the standard python distribution includes programming environment called idle that you may use for working on the programs in this book let' illustrate the use of module file by writing and running complete program our program will illustrate mathematical concept known as chaos here is the program as we would type it into idle or some other editor and save in module filefilechaos py simple program illustrating chaotic behavior def main()print("this program illustrates chaotic function" eval(input("enter number between and ")for in range( ) ( xprint(xmain(this file should be saved with the name chaos py the py extension indicates that this is python module you can see that this particular example contains lines to define new function called main (programs are often placed in function called main the last line of the file is the command to invoke this function don' worry if you don' understand what main actually doeswe will discuss it in the next section the point here is that once we have program in module filewe can run it any time we want this program can be run in number of different ways that depend on the actual operating system and programming environment that you are using if you are using windowing systemyou can run python program by clicking (or double-clickingon the module file' icon in command line situationyou might type command like python chaos py if you are using idle (or another programming environmentyou can run program by opening it in the editor and then selecting command like importrunor execute |
19,512 | one method that should always work is to start python shell and then import the file here is how that looksimport chaos this program illustrates chaotic function enter number between and typing the first line import chaos tells the python interpreter to load the chaos module from the file chaos py into main memory notice that did not include the py extension on the import linepython assumes the module will have py extension as python imports the module fileeach line executes it' just as if we had typed them oneby-one at the interactive python prompt the def in the module causes python to create the main function when python encounters the last line of the modulethe main function is invokedthus running our program the running program asks the user to enter number between and (in this casei typed "and then prints out series of numbers when you first import module file in this waypython creates companion file with pyc extension in this examplepython creates another file on the disk called chaos pyc this is an intermediate file used by the python interpreter technicallypython uses hybrid compiling/interpreting process the python source in the module file is compiled into more primitive instructions called byte code this byte code (the pycfile is then interpreted having pyc file available makes importing module faster the second time around howeveryou may delete the byte code files if you wish to save disk spacepython will automatically recreate them as needed module needs to be imported into session only once after the module has been loadedwe can run the program again by asking python to execute the main command we do this by using special dot notation typing chaos main(tells python to invoke the main function in the chaos module continuing with our examplehere is how it looks when we rerun the program with as the inputchaos main(this program illustrates chaotic function enter number between and |
19,513 | computers and programs inside python program the output from the chaos program may not look very excitingbut it illustrates very interesting phenomenon known to physicists and mathematicians let' take look at this program line by line and see what it does don' worry about understanding every detail right awaywe will be returning to all of these ideas in the next the first two lines of the program start with the characterfilechaos py simple program illustrating chaotic behavior these lines are called comments they are intended for human readers of the program and are ignored by python the python interpreter always skips any text from the pound sign (#through the end of line the next line of the program begins the definition of function called maindef main()strictly speakingit would not be necessary to create main function since the lines of module are executed as they are loadedwe could have written our program without this definition that isthe module could have looked like thisfilechaos py simple program illustrating chaotic behavior print("this program illustrates chaotic function" eval(input("enter number between and ")for in range( ) ( xprint(xthis version is bit shorterbut it is customary to place the instructions that comprise program inside of function called main one immediate benefit of this approach was illustrated aboveit allows us to run the program by simply invoking chaos main(we don' have to restart the python shell in order to run it againwhich would be necessary in the main-less case the first line inside of main is really the beginning of our program |
19,514 | print("this program illustrates chaotic function"this line causes python to print message introducing the program when it runs take look at the next line of the programx eval(input("enter number between and ")here is an example of variable variable is used to give name to value so that we can refer to it at other points in the program the entire line is statement to get some input from the user there' quite bit going on in this lineand we'll discuss the details in the next for nowyou just need to know what it accomplishes when python gets to this statementit displays the quoted message enter number between and and then pauseswaiting for the user to type something on the keyboard and press the key the value that the user types in is then stored as the variable in the first example shown abovethe user entered which becomes the value of the next statement is an example of loop for in range( ) loop is device that tells python to do the same thing over and over again this particular loop says to do something times the lines indented underneath the loop heading are the statements that are done times these form the body of the loop ( xprint(xthe effect of the loop is exactly the same as if we had written the body of the loop timesx ( xprint(xx ( xprint(xx ( xprint(xx ( xprint(xx ( xprint(xx ( xprint(xx ( xprint(xx ( xprint(xx ( |
19,515 | computers and programs print(xx ( xprint(xobviouslyusing the loop instead saves the programmer lot of trouble but what exactly do these statements dothe first one performs calculation ( xthis is called an assignment statement the part on the right side of the is mathematical expression python uses the character to indicate multiplication recall that the value of is (from the input abovethe computed value is ( )( or once the value on the right-hand side is computedit is saved as (or assigned tothe variable that appears on the left-hand side of the =in this case the new value of ( replaces the old value ( the second line in the loop body is type of statement we have encountered beforea print statement print(xwhen python executes this statement the current value of is displayed on the screen sothe first number of output is remember the loop executes times after printing the value of xthe two statements of the loop are executed again ( xprint of coursenow has the value so the formula computes new value of as ( )( )which is can you see how the current value of is used to compute new value each time around the loopthat' where the numbers in the example run came from you might try working through the steps of the program yourself for different input value (say then run the program using python and see how well you did impersonating computer chaos and computers said above that the chaos program illustrates an interesting phenomenon what could be interesting about screen full of numbersif you try out the program for yourselfyou'll find thatno matter what number you start withthe results are always similarthe program spits back seemingly random numbers between and as the program runsthe value of seems to jump aroundwellchaotically the function computed by this program has the general formk( )( )where in this case is this is called logistic function it models certain kinds of unstable electronic circuits and is also sometimes used to predict population under limiting conditions repeated application of the |
19,516 | logistic function can produce chaos although our program has well defined underlying behaviorthe output seems unpredictable an interesting property of chaotic functions is that very small differences in the initial value can lead to large differences in the result as the formula is repeatedly applied you can see this in the chaos program by entering numbers that differ by only small amount here is the output from modified program that shows the results for initial values of and side by sideinput with very similar starting valuesthe outputs stay similar for few iterationsbut then differ markedly by about the fifth iterationthere no longer seems to be any relationship between the two models these two features of our chaos programapparent unpredictability and extreme sensitivity to initial valuesare the hallmarks of chaotic behavior chaos has important implications for computer science it turns out that many phenomena in the real world that we might like to model and predict with our computers exhibit just this kind of chaotic behavior you may have heard of the so-called butterfly effect computer models that are used to simulate and predict weather patterns are so sensitive that the effect of single butterfly flapping its wings in new jersey might make the difference of whether or not rain is predicted in peoria it' very possible that even with perfect computer modelingwe might never be able to measure existing weather conditions accurately enough to predict weather more than few days in advance the measurements simply can' be precise enough to make the predictions accurate over longer time frame as you can seethis small program has valuable lesson to teach users of computers as amazing as computers arethe results that they give us are only as useful as the mathematical models on which the programs are based computers can give incorrect results because of errors in programsbut even correct programs may produce erroneous results if the models are wrong or the initial inputs are not accurate enough |
19,517 | summary this has introduced computerscomputer scienceand programming here is summary of some of the key conceptsa computer is universal information-processing machine it can carry out any process that can be described in sufficient detail description of the sequence of steps for solving particular problem is called an algorithm algorithms can be turned into software (programsthat determines what the hardware (physical machinecan and does accomplish the process of creating software is called programming computer science is the study of what can be computed computer scientists use the techniques of designanalysisand experimentation computer science is the foundation of the broader field of computing which includes areas such as networkingdatabasesand information management systemsto name few basic functional view of computer system comprises central processing unit (cpu)main memorysecondary memoryand input and output devices the cpu is the brain of the computer that performs simple arithmetic and logical operations information that the cpu acts on (data and programsis stored in main memory (rammore permanent information is stored on secondary memory devices such as magnetic disksflash memoryand optical devices information is entered into the computer via input devicesand output devices display the results programs are written using formal notation known as programming language there are many different languagesbut all share the property of having precise syntax (formand semantics (meaningcomputer hardware only understands very low-level language known as machine language programs are usually written using human-oriented high-level languages such as python high-level language must either be compiled or interpreted in order for the computer to understand it high-level languages are more portable than machine language python is an interpreted language one good way to learn about python is to use an interactive shell for experimentation python program is sequence of commands (called statementsfor the python interpreter to execute python includes statements to do things such as print output to the screenget input from the usercalculate the value of mathematical expressionand perform sequence of statements multiple times (loopa mathematical model is called chaotic if very small changes in the input lead to large changes in the resultsmaking them seem random or unpredictable the models of many real-world phenomena exhibit chaotic behaviorwhich places some limits on the power of computing |
19,518 | exercises review questions true/false computer science is the study of computers the cpu is the "brainof the computer secondary memory is also called ram all information that computer is currently working on is stored in main memory the syntax of language is its meaningand semantics is its form function definition is sequence of statements that defines new command programming environment refers to place where programmers work variable is used to give name to value so it can be referred to in other places loop is used to skip over section of program chaotic function can' be computed by computer multiple choice what is the fundamental question of computer scienceahow fast can computer computebwhat can be computedcwhat is the most effective programming languagedhow much money can programmer make an algorithm is like anewspaper bvenus flytrap cdrum drecipe problem is intractable when ayou cannot reverse its solution bit involves tractors cit has many solutions dit is not practical to solve which of the following is not an example of secondary memoryaram bhard drive cusb flash drive dcd-rom |
19,519 | computer languages designed to be used and understood by humans are anatural languages bhigh-level computer languages cmachine languages dfetch-execute languages statement is aa translation of machine language ba complete computer command ca precise description of problem da section of an algorithm one difference between compiler and an interpreter is aa compiler is program ba compiler is used to translate high-level language into machine language ca compiler is no longer needed after program is translated da compiler processes source code by conventionthe statements of program are often placed in function called aimport bmain cprogram didle which of the following is not true of commentsathey make program more efficient bthey are intended for human readers cthey are ignored by python din pythonthey begin with pound sign (# the items listed in the parentheses of function definition are called aparentheticals bscripts ccomments dparameters discussion compare and contrast the following pairs of concepts from the (ahardware vs software (balgorithm vs program (cprogramming language vs natural language (dhigh-level language vs machine language (einterpreter vs compiler (fsyntax vs semantics list and explain in your own words the role of each of the five basic functional units of computer depicted in figure |
19,520 | write detailed algorithm for making peanut butter and jelly sandwich (or some other everyday activityyou should assume that you are talking to someone who is conceptually able to do the taskbut has never actually done it before for exampleyou might be telling young child as you will learn in later many of the numbers stored in computer are not exact valuesbut rather close approximations for examplethe value might be stored as usuallysuch small differences are not problemhowevergiven what you have learned about chaotic behavior in you should realize the need for caution in certain situations can you think of examples where this might be problemexplain trace through the chaos program from section by hand using as the input value show the sequence of output that results programming exercises start up an interactive python session and try typing in each of the following commands write down the results you see (aprint("helloworld!"(bprint("hello""world!"(cprint( (dprint( (eprint( (fprint( (gprint(" " "(hprint(" =" (iprint( (jprint( * (kprint( enter and run the chaos program from section try it out with various values of input to see that it functions as described in the modify the chaos program using in place of as the multiplier in the logistic function your modified line of code should look like thisx ( xrun the program for various input values and compare the results to those obtained from the original program write short paragraph describing any differences that you notice in the behavior of the two versions |
19,521 | modify the chaos program so that it prints out values instead of modify the chaos program so that the number of values to print is determined by the user you will have to add line near the top of the program to get another value from the usern eval(input("how many numbers should print")then you will need to change the loop to use instead of specific number the calculation performed in the chaos program can be written in number of ways that are algebraically equivalent write version of the chaos program for each of the following ways of doing the computation have your modified programs print out iterations of the function and compare the results when run on the same input ( ( ( ( ( explain the results of this experiment hintsee discussion question number above (advancedmodify the chaos program so that it accepts two inputs and then prints table with two columns similar to the one shown in section (noteyou will probably not be able to get the columns to line up as nicely as those in the example discusses how to print numbers with fixed number of decimal places |
19,522 | writing simple programs objectives to know the steps in an orderly software development process to understand programs following the inputprocessoutput (ipopattern and be able to modify them in simple ways to understand the rules for forming valid python identifiers and expressions to be able to understand and write python statements to output information to the screenassign values to variablesget information entered from the keyboardand perform counted loop the software development process as you saw in the previous it is easy to run programs that have already been written the harder part is actually coming up with program in the first place computers are very literaland they must be told what to do right down to the last detail writing large programs is daunting challenge it would be almost impossible without systematic approach the process of creating program is often broken down into stages according to the information that is produced in each phase in nutshellhere' what you should doanalyze the problem 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 isyou cannot begin to solve it determine specifications describe exactly what your program will do at this pointyou should not worry about how your program will workbut rather about 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 |
19,523 | writing simple programs create 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(sthat will meet the specifications implement the design translate the design into computer language and put it into the computer in this bookwe 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 program during the debugging phaseyour goal is to find errorsso you should try everything you can think of that might "breakthe program it' good to keep in mind the old maxim"nothing is foolproof because fools are too ingenious maintain the program continue developing the program in response to the needs of your users most programs are never really finishedthey keep evolving over years of use example programtemperature converter let' go through the steps of the software development process with simple real-world example involving fictional computer science studentsusan computewell susan is spending year studying in germany she has no problems with languageas she is fluent in many languages (including pythonher problem is that she has hard time figuring out the temperature in the morning so that she knows how to dress for the day susan listens to the weather report each morningbut the temperatures are given in degrees celsiusand she is used to fahrenheit fortunatelysusan has an idea to solve the problem being computer science majorshe never goes anywhere without her laptop computer she thinks it might be possible that computer program could help her out susan begins with an analysis of her problem in this casethe problem is pretty clearthe radio announcer gives temperatures in degrees celsiusbut susan only comprehends temperatures that are in degrees fahrenheit nextsusan considers the specifications of program that might help her out what should the input beshe decides that her program will allow her to type in the temperature in degrees celsius and the outputthe program will display the temperature converted into degrees fahrenheit now she needs to specify the exact relationship of the output to the input susan does some quick figuring she knows that degrees celsius (freezingis equal to degrees fahrenheitand celsius (boilingis equal to fahrenheit with this information she computes the ratio of fahrenheit to celsius degrees as - - using to represent the fahrenheit temperature and for celsiusthe conversion formula will have the form + for some constant plugging in and for and respectivelysusan immediately sees that sothe final formula for the relationship is that seems an adequate specification |
19,524 | notice that this describes one of many possible programs that could solve this problem if susan had background in the field of artificial intelligence (ai)she might consider writing program that would actually listen to the radio announcer to get the current temperature using speech recognition algorithms for outputshe might have the computer control robot that goes to her closet and picks an appropriate outfit based on the converted temperature this would be much more ambitious projectto say the leastcertainlythe robot program would also solve the problem identified in the problem analysis the purpose of specification is to decide exactly what this particular program will do to solve problem susan knows better than to just dive in and start writing program without first having clear idea of what she is trying to build susan is now ready to design an algorithm for her problem she immediately realizes that this is simple algorithm that follows standard patterninputprocessoutput (ipoher program will prompt the user for some input information (the celsius temperature)process it to convert to fahrenheit temperatureand then output the result by displaying it on the computer screen susan could write her algorithm down in computer language howeverthe precision required to write it out formally tends to stifle the creative process of developing the algorithm insteadshe writes her algorithm using pseudocode pseudocode is just precise english that describes what 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 susan' completed algorithminput the temperature in degrees celsius (call it celsiuscalculate fahrenheit as ( / )celsius output fahrenheit the next step is to translate this design into python program this is straightforwardas each line of the algorithm turns into corresponding line of python code convert py program to convert celsius temps to fahrenheit bysusan computewell def main()celsius eval(input("what is the celsius temperature")fahrenheit / celsius print("the temperature is"fahrenheit"degrees fahrenheit "main(see if you can figure out what each line of this program does don' worry if some parts are bit confusing they will be discussed in detail in the next section after completing her programsusan tests it to see how well it works she uses inputs for which she knows the correct answers here is the output from two of her tests |
19,525 | writing simple programs what is the celsius temperature the temperature is degrees fahrenheit what is the celsius temperature the temperature is degrees fahrenheit you can see that susan used the values of and to test her program it looks pretty goodand she is satisfied with her solution she is especially pleased that no debugging seems necessary (which is very unusual elements of programs now that you know something about the programming processyou are almost ready to start writing programs on your own before doing thatthoughyou need 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 bit tediousbut you will have to master these basics before plunging into more interesting waters names you have already seen that names are an important part of programming we give names to modules ( convertand to the functions within modules ( mainvariables are used to give names to values ( celsius and fahrenheittechnicallyall these names are called identifiers python has some rules about how identifiers are formed every identifier must begin with letter or underscore (the "_characterwhich may be followed by any sequence of lettersdigitsor underscores this implies that single identifier cannot contain any spaces according to these rulesall of the following are legal names in pythonx celsius spam spam spamandeggs spam_and_eggs identifiers are case-sensitiveso spamspamspamand spam are all different names to python for the most partprogrammers 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 or keywords and cannot be used as ordinary identifiers the complete list of python keywords is shown in table |
19,526 | false none true and as assert break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield table python keywords expressions programs manipulate data so farwe have seen two different kinds of data in our example programsnumbers and text we'll examine these different data types in great detail in later for nowyou just need to keep in mind that all data has to be stored on the computer in some digital formatand different types of data are stored in different ways the fragments of program code that produce or calculate new data values are called expressions the simplest kind of expression is literal literal is used to indicate specific value in chaos py you can find the numbers and the convert py program contains and these are all examples of numeric literalsand their meaning is obvious representswell (the number our programs also manipulated textual data in some simple ways computer scientists refer to textual data as strings you can think of string as just sequence of printable characters string literal is indicated in python by enclosing the characters in quotation marks (""if you go back and look at our example programsyou will find number of string literals such as"helloand "enter number between and these literals produce strings containing the quoted characters note that the quotes themselves are not part of the string they are just the mechanism to tell python to create string the process of turning an expression into an underlying data type is called evaluation when you type an expression into python shellthe shell evaluates the expression and prints out textual representation of the result consider this small interaction "hello'hello" ' notice that when the shell shows the value of stringit puts the sequence of characters in single quotes this is way of letting us know that the value is actually textnot number (or other data typein the last interactionwe see that the expression " produces stringnot number in this casepython is actually storing the characters " and " ,not representation of the number |
19,527 | if that' confusing right nowdon' worry too much about itit will become clearer when we discuss these data types in later simple identifier can also be an expression we use identifiers as variables to give names to values when an identifier appears as an expressionits value is retrieved to provide result for the expression here is an interaction with the python interpreter that illustrates the use of variables as expressionsx print( print(spamtraceback (most recent call last)file ""line in nameerrorname 'spamis not first the variable is assigned the value (using the numeric literal in the second line of interactionwe are asking python to evaluate the expression in responsethe python shell prints out which is the value that was just assigned to of coursewe get the same result when we explicitly ask python to print using print statement the last interaction shows what happens when we try to use variable that has not been assigned value python cannot find valueso it reports nameerror this says that there is no value with that name the important lesson here is that variable must always be assigned value before it can be used in an expression more complex and interesting expressions can be constructed by combining simpler expressions with operators for numberspython provides the normal set of mathematical operationsadditionsubtractionmultiplicationdivisionand exponentiation the corresponding python operators are+-*/and *here are some examples of complex expressions from chaos py and convert py ( / celsius spaces are irrelevant within an expression the last expression could have been written / *celsius+ and the result would be exactly the same usually it' good idea to place some spaces in expressions to make them easier to read python' mathematical operators obey the same rules of precedence and associativity that you learned in your math classesincluding 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 numeric expressionsbut you can nest them if necessary to create expressions like this (( * (spam ** by the waypython also provides operators for strings for exampleyou can "addstrings |
19,528 | "bat"man'batmanthis is called concatenation as you can seethe effect is to create new string that is the result of "gluingthe strings together you'll see lot more string operations in output statements now that you have the basic building blocksidentifier and expressionyou are ready for more complete description of various python statements you already know that information can be displayed on screen using python' built-in function print so farwe have looked at few examplesbut have not yet explained the print function in detail like all programming languagespython has precise set of rules for the syntax (formand semantics (meaningof each statement computer scientists have developed sophisticated notations called meta-languages for describing programming languages in this book we will rely on simple template notation to illustrate the syntax of various statements since print is built-in functiona print statement has the same general form as any other function invocation we type the function name print followed by parameters listed in parentheses here is how the print statement looks using our template notationprint(print(these two templates show two forms of the print statement the first indicates that print statement can consist of the function name print followed by parenthesized sequence of expressionswhich are separated by commas the angle bracket notation (in the template is used to indicate "slotsthat are filled in by other fragments of python code the name inside the brackets indicates what is missingexpr stands for an expression the ellipses ("indicate an indefinite series (of expressionsin this caseyou don' actually type the dots the second version of the statement shows that it' also legal to have print without any expressions to print as far as semantics are concerneda print statement displays information in textual form any supplied expressions are evaluated left to rightand the resulting values are displayed on line of output in left-to-right fashion by defaulta single blank space character is placed between the displayed values as an examplethis sequence of print statementsprint( + print( print(print("the answer is" produces this output |
19,529 | writing simple programs the answer is the last statement illustrates how string literal expressions are often used in print statements as convenient way of labeling output notice that successive print statements normally display on separate lines of the screen bare print(no parametersproduces blank line of output underneathwhat' really happening is that the print function automatically appends some ending text after all of the supplied expressions are printed by defaultthat ending text is special marker character (denoted as "\ "that signals the end of line we can modify that behavior by including an additional parameter that explicitly overrides this default this is done using special syntax for named or keyword parameters template for the print statement including the keyword parameter to specify the ending-text looks like thisprint(end="\ "the keyword for the named parameter is end and it is given value using notationsimilar to variable assignment notice in the template have shown its default valuethe end-of-line character this is standard way of showing what value keyword parameter will have when it is not explicitly given some other value one common use of the end parameter in print statements is to allow multiple prints to build up single line of output for exampleprint("the answer is"end="print( produces the single line of outputthe answer is notice how the output from the first print statement ends with space ("rather than an endof-line the output from the second statement appears immediately following the space assignment statements one of the most important kinds of statements in python is the assignment statement we've already seen number of these in our previous examples simple assignment the basic assignment statement has this form |
19,530 | 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 valuewhich is then associated with the variable named on the left side here are some of the assignments we've already seenx ( xfahrenheit celsius variable can be assigned many times it always retains the value of the most recent assignment here is an interactive python session that demonstrates the pointmyvar myvar myvar myvar myvar myvar myvar the last assignment statement shows how the current value of variable can be used to update its value in this case simply added one to the previous value the chaos py program from did something similarthough bit more complex rememberthe values of variables can changethat' why they're called variables sometimes it' helpful to think of variable as sort of named storage location in computer memorya box that we can put value in when the variable changesthe old value is erased and new one written in figure shows how we might picture the effect of using this model this is exactly the way assignment works in some computer languages it' also very simple way to view the effect of assignmentand you'll find pictures similar to this throughout the book after before figure variable as box view of python assignment statements are actually slightly different from the "variable as boxmodel in pythonvalues may end up anywhere in memoryand variables are used to refer to them assigning variable is like putting one of those little yellow sticky notes on the value and saying"this |
19,531 | is figure gives more accurate picture of the effect of assignment in python an arrow is used to show which value variable refers to notice that the old value doesn' get erased by the new onethe variable simply switches to refer to the new value the effect is like moving the sticky note from one object to another this is the way assignment actually works in pythonso you'll see some of these sticky-note style pictures sprinkled throughout the book as well before after figure variable as sticky note (pythonview of by the wayeven though the assignment statement doesn' directly cause the old value of variable to be erased and overwrittenyou don' have to worry about computer memory getting filled up with the "discardedvalues when value is no longer referred to by any variableit is no longer useful python will automatically clear these values out of memory so that the space can be used for new values this is like going through your closet and tossing out anything that doesn' have sticky note to label it in factthis process of automatic memory management is actually called garbage collection assigning input the purpose of an input statement is to get some information from the user of program and store it into variable some programming languages have special statement to do this in pythoninput is accomplished using an assignment statement combined with built-in function called input the exact form of an input statement depends on what type of data you are trying to get from the user for textual inputthe statement will look like thisinput(here is string expression that is used to prompt the user for inputthe prompt is almost always string literal ( some text inside of quotation markswhen python encounters call to inputit prints the prompt on the screen python then pauses and waits for the user to type some text and press the key whatever the user types is then stored as string consider this simple interactionname input("enter your name" |
19,532 | enter your namejohn yaya name 'john yayaexecuting the input statement caused python to print out the prompt "enter your name:and then the interpreter paused waiting for user input in this examplei typed john yaya as resultthe string 'john yayais remembered in the variable name evaluating name gives back the string of characters that typed when the user input is numberwe need slightly more complicated form of input statementeval(input()here 've added another built-in python function eval that is "wrapped aroundthe input function as you might guesseval is short for "evaluate in this formthe text typed by the user is evaluated as an expression to produce the value that is stored into the variable sofor examplethe string " becomes the number if you look back at the example programs so faryou'll see couple examples where we've gotten numbers from the user like this eval(input("please enter number between and ")celsius eval(input("what is the celsius temperature")the important thing to remember is that you need to eval the input when you want number instead of some raw text ( stringif you are reading the example programs carefullyyou probably noticed the blank space inside the quotes at the end of all these prompts usually put space at the end of prompt so that the input that the user types does not start right next to the prompt putting space in makes the interaction easier to read and understand although our numeric examples specifically prompted the user to enter numberwhat the user types in this case is just numeric literal-- simple python expression in factany valid expression would be just as acceptable consider the following interaction with the python interpreterans eval(input("enter an expression")enter an expression print(ans herewhen prompted to enter an expressionthe user typed " python evaluated this expression (via evaland assigned the value to the variable ans when printedwe see that ans got the value as expected in sensethe input-eval combination is like delayed expression the example interaction produced exactly the same result as if we had simply written ans the difference is that the expression was supplied by the user at the time the statement was executed instead of being determined when the statement was written by the programmer thusthe user can supply formulas for program to evaluate |
19,533 | simultaneous assignment there is an alternative form of the assignment statement that allows us to calculate several values all at the same time it looks like thisthis is called simultaneous assignment semanticallythis tells python to evaluate all the expressions on the right-hand side and then assign these values to the corresponding variables named on the left-hand side here' an examplesumdiff +yx- here sum would get the sum of and and diff would get the difference this form of assignment seems strange at firstbut it can prove remarkably useful here' an examplesuppose you have two variables and and you want to swap the values that isyou want the value currently stored in to be in and the value that is currently in to be stored in at firstyou might think this could be done with two simple assignments this doesn' work we can trace the execution of these statements step-by-step to see why suppose and start with the values and let' examine the logic of the program to see how the variables change the following sequence uses comments to describe what happens to the variables as these two statements are executedvariables initial values now final see how the first statement clobbers the original value of by assigning to it the value of ywhen we then assign to in the second stepwe just end up with two copies of the original value one way to make the swap work is to introduce an additional variable that temporarily remembers the original value of temp temp let' walk-through this sequence to see how it works |
19,534 | variables initial values temp temp temp no value yet as you can see from the final values of and ythe swap was successful in this case this sort of three-way shuffle is common in other programming languages in pythonthe simultaneous assignment statement offers an elegant alternative here is simpler python equivalentxy yx because the assignment is simultaneousit avoids wiping out one of the original values simultaneous assignment can also be used to get multiple numbers from the user in single input consider this program for averaging exam scoresavg py simple program to average two exam scores illustrates use of multiple input def main()print("this program computes the average of two exam scores "score score eval(input("enter two scores separated by comma")average (score score print("the average of the scores is:"averagemain(the program prompts for two scores separated by comma suppose the user types the effect of the input statement is then the same as if we had done this assignmentscore score we have gotten value for each of the variables in one fell swoop this example used just two valuesbut it could be generalized to any number of inputs of coursewe could have just gotten the input from the user using separate input statements score eval(input("enter the first score")score eval(input("enter the second score") |
19,535 | writing simple programs in some ways this may be betteras the separate prompts are more informative for the user in this example the decision as to which approach to take is largely matter of taste sometimes getting multiple values in single input provides more intuitive user interfaceso it' nice technique to have in your toolkit just remember that the multiple values trick will not work for string (nonevaledinputwhen the user types comma it will be just another character in the input string the comma only becomes separator when the string is subsequently evaluated definite loops you already know that programmers use loops to execute sequence of statements multiple times in succession the simplest kind of loop is called definite loop this is loop that will execute definite number of times that isat the point in the program when the loop beginspython knows how many times to go around (or iteratethe body of the loop for examplethe chaos program in used loop that always executed exactly ten times for in range( ) ( xprint(xthis particular loop pattern is called counted loopand it is built using python for statement before considering this example in detaillet' take look at what for loops are all about python for loop has this general formfor in the body of the loop can be any sequence of python statements the extent of the body is indicated by its indentation under the loop heading (the for in partthe variable after the keyword for is called the loop index it takes on each successive value in the sequenceand the statements in the body are executed once for each value often the sequence portion consists of list of values lists are very important concept in pythonand you will learn more about them in upcoming for nowit' enough to know that you can create simple list by placing sequence of expressions in square brackets some interactive examples help to illustrate the pointfor in [ ]print( for odd in [ ] |
19,536 | print(odd odd can you see what is happening in these two examplesthe body of the loop is executed using each successive value in the list the length of the list determines the number of times the loop executes in the first examplethe list contains the four values through and these successive values of are simply printed in the second exampleodd takes on the values of the first five odd natural numbersand the body of the loop prints the squares of these numbers nowlet' go back to the example that began this section (from chaos pylook again at the loop headingfor in range( )comparing this to the template for the for loop shows that the last portionrange( )must be some kind of sequence it turns out that range is built-in python function for generating sequence of numbers "on the fly you can think of range as sort of implicit description of sequence of numbers to get handle on what range actually doeswe can ask python to turn range into plain-old list using another built-in functionlistlist(range( )turns range( into an explicit list [ do you see what is happening herethe expression range( produces the sequence of numbers through the loop using range( is equivalent to one using list of those numbers for in [ ]in generalrange(will produce sequence of numbers that starts with and goes up tobut not does not includethe value of if you think about ityou will see that the value of the expression determines the number of items in the resulting sequence in chaos py we did not even care what values the loop index variable used (since was not referred to anywhere in the loop bodywe just needed sequence length of to make the body execute times as mentioned abovethis pattern is called counted loopand it is very common way to use definite loops when you want to do something in your program certain number of timesuse for loop with suitable range for in range()the value of the expression determines how many times the loop executes the name of the index variable doesn' really matter muchprogrammers often use or as the loop index variable for |
19,537 | counted loops just be sure to use an identifier that you are not using for any other purpose otherwise you might accidentally wipe out value that you will need later the interesting and useful thing about loops is the way that they alter the "flow of controlin program usually we think of computers as executing series of instructions in strict sequence introducing loop causes python to go back and do some statements over and over again statements like the for loop are called control structures because they control the execution of other parts of the program some programmers find it helpful to think of control structures in terms of pictures called flowcharts flowchart is diagram that uses boxes to represent different parts of program and arrows between the boxes to show the sequence of events when the program is running figure depicts the semantics of the for loop as flowchart more items in no yes next item figure flowchart of for loop if you are having trouble understanding the for loopyou might find it useful to study the flowchart the diamond shaped box in the flowchart represents decision in the program when python gets to the loop headingit checks to see if there are any (moreitems left in the sequence if the answer is yesthe loop index variable is assigned the next item in the sequenceand then the loop body is executed once the body is completethe program goes back to the loop heading and checks for another value in the sequence the loop quits when there are no more itemsand the program moves on to the statements that come after the loop |
19,538 | example programfuture value let' close the with one more example of the programming process in action we want to develop program to determine the future value of an investment we'll start with an analysis of the problem you know that money deposited in bank account earns interestand this interest accumulates as the years pass how much will an account be worth ten years from nowobviouslyit depends on how much money we start with (the principaland how much interest the account earns given the principal and the interest ratea program should be able to calculate the value of the investment ten years into the future we continue by developing the exact specifications for the program rememberthis is description of what the program will do what exactly should the inputs bewe need the user to enter the initial amount to investthe principal we will also need some indication of how much interest the account earns this depends both on the interest rate and how often the interest is compounded one simple way of handling this is to have the user enter an annual percentage rate whatever the actual interest rate and compounding frequencythe annual rate tells us how much the investment accrues in one year if the annual interest is %then $ investment will grow to $ in one year' time how should the user represent an annual rate of %there are number of reasonable choices let' assume the user supplies decimalso the rate would be entered as this leads us to the following specificationprogram future value inputs principal the amount of money being invested in dollars apr the annual percentage rate expressed as decimal number output the value of the investment years into the future relationship value after one year is given by principal( aprthis formula needs to be applied times next we design an algorithm for the program we'll use pseudocodeso that we can formulate our ideas without worrying about all the rules of python given our specificationthe algorithm seems straightforward print an introduction input the amount of the principal (principalinput the annual percentage rate (aprrepeat timesprincipal principal ( aproutput the value of principal |
19,539 | writing simple programs if you know little bit about financial math (or just some basic algebra)you probably realize that the loop in this design is not strictly necessarythere is formula for calculating future value in single step using exponentiation have used loop here both to illustrate another counted loopand also because this version will lend itself to some modifications that are discussed in the programming exercises at the end of the in any casethis design illustrates that sometimes an algorithmic approach to calculation can make the mathematics easier knowing how to calculate the interest for just one year allows us to calculate any number of years into the future now that we've thought the problem all the way through in pseudocodeit' time to put our new python knowledge to work and develop program each line of the algorithm translates into statement of python print an introduction (print statementsection print("this program calculates the future value"print("of -year investment "input the amount of the principal (numeric inputsection principal eval(input("enter the initial principal")input the annual percentage rate (numeric inputsection apr eval(input("enter the annual interest rate")repeat times(counted loopsection for in range( )calculate principal principal ( apr(simple assignmentsection principal principal ( aproutput the value of the principal (print statementsection print("the value in years is:"principalall of the statement types in this program have been discussed in detail in this if you have any questionsyou should go back and review the relevant descriptions notice especially the counted loop pattern is used to apply the interest formula times that about wraps it up here is the completed programfutval py program to compute the value of an investment carried years into the future def main()print("this program calculates the future value"print("of -year investment " |
19,540 | principal eval(input("enter the initial principal")apr eval(input("enter the annual interest rate")for in range( )principal principal ( aprprint("the value in years is:"principalmain(notice that have added few blank lines to separate the inputprocessingand output portions of the program strategically placed "white spacecan help make your programs more readable that' as far as ' taking this examplei leave the testing and debugging as an exercise for you summary this has covered lot of ground laying out both the process that is used to develop programs and the details of python that are necessary to implement simple programs here is quick summary of some of the key pointswriting programs requires systematic approach to problem solving and involves the following steps problem analysisstudying the problem to be solved program specificationdeciding exactly what the program will do designwriting an algorithm in pseudocode implementationtranslating the design into programming language testing/debuggingfinding and fixing errors in the program maintenancekeeping the program up to date with evolving needs many simple programs follow the inputprocessoutput (ipopattern programs are composed of statements that are built from identifiers and expressions identifiers are namesthey begin with an underscore or letter which can be followed by combination of letterdigitor underscore characters identifiers in python are case sensitive expressions are the fragments of program that produce data an expression can be composed of the following componentsliterals literal is representation of specific value for example is literal representing the number three |
19,541 | variables variable is an identifier that stores value operators operators are used to combine expressions into more complex expressions for examplein the operators and are used the python operators for numbers include the usual arithmetic operations of addition (+)subtraction (-)multiplication (*)division (/)and exponentiation (**the python output statement print displays the values of series of expressions to the screen in pythonassignment of value to variable is done using the equal sign (=using assignmentprograms can get input from the keyboard python also allows simultaneous assignmentwhich is useful for getting multiple input values with single prompt definite loops are loops that execute known number of times the python for statement is definite loop that iterates through sequence of values python list is often used in for loop to provide sequence of values for the loop one important use of for statement is in implementing counted loopwhich is loop designed specifically for the purpose of repeating some portion of the program specific number of times counted loop in python is created by using the built-in range function to produce suitably sized list of numbers exercises review questions true/false the best way to write program is to immediately type in some code and then debug it until it works an algorithm can be written without using programming language programs no longer require modification after they are written and debugged python identifiers must start with letter or underscore keywords make good variable names expressions are built from literalsvariablesand operators in pythonx is legal statement python does not allow the input of multiple values with single statement counted loop is designed to iterate specific number of times in flowchartdiamonds are used to show statementsand rectangles are used for decision points |
19,542 | multiple choice which of the following is not step in the software development processaspecification btesting/debugging cfee setting dmaintenance what is the correct formula for converting celsius to fahrenheitaf / ( bf / ( cf ac df - - the process of describing exactly what computer program will do to solve problem is called adesign bimplementation cprogramming dspecification which of the following is not legal identifieraspam bspam spam dspam which of the following are not used in expressionsavariables bstatements coperators dliterals fragments of code that produce or calculate new data values are called aidentifiers bexpressions cproductive clauses dassignment statements which of the following is not part of the ipo patternainput bprogram cprocess doutput the template for in range(describes aa general for loop ban assignment statement ca flowchart da counted loop which of the following is the most accurate model of assignment in pythonasticky-note bvariable-as-box csimultaneous dplastic-scale in pythongetting user input is done with special expression called afor bread csimultaneous assignment dinput discussion list and describe in your own words the six steps in the software development process write out the chaos py program (section and identify the parts of the program as followscircle each identifier |
19,543 | underline each expression put comment at the end of each line indicating the type of statement on that line (outputassignmentinputloopetc explain the relationships among the conceptsdefinite loopfor loopand counted loop show the output from the following fragments(afor in range( )print( (bfor in [ , , , , ]print(dend="(cfor in range( )print("hello"(dfor in range( )print( ** why is it good idea to first write out an algorithm in pseudocode rather than jumping immediately to python code the python print function supports other keyword parameters besides end one of these other keyword parameters is sep what do you think the sep parameter doeshintsep is short for separator test your idea either by trying it interactively or by consulting the python documentation what do you think will happen if the following code is executedprint("start"for in range( )print("hello"print("end"look at the flowchart for the for statement in the to help you figure this out then test your prediction by trying out these lines in program programming exercises user-friendly program should print an introduction that tells the user what the program does modify the convert py program (section to print an introduction modify the avg py program (section to find the average of three exam scores modify the convert py program (section with loop so that it executes times before quitting ( it converts temperatures in row |
19,544 | modify the convert py program (section so that it computes and prints table of celsius temperatures and the fahrenheit equivalents every degrees from to modify the futval py program (section so that the number of years for the investment is also user input make sure to change the final message to reflect the correct number of years suppose you have an investment plan where you invest certain fixed amount every year modify futval py to compute the total accumulation of your investment the inputs to the program will be the amount to invest each yearthe interest rateand the number of years for the investment as an alternative to aprthe interest accrued on an account is often described in terms of nominal rate and the number of compounding periods for exampleif the interest rate is and the interest is compounded quarterlythe account actually earns / interest every months modify the futval py program to use this method of entering the interest rate the program should prompt the user for the yearly rate (rateand the number of times that the interest is compounded each year (periodsto compute the value in ten yearsthe program will loop periods times and accrue rate/period interest on each iteration write program that converts temperatures from fahrenheit to celsius write program that converts distances measured in kilometers to miles one kilometer is approximately miles write program to perform unit conversion of your own choosing make sure that the program prints an introduction that explains what it does write an interactive python calculator program the program should allow the user to type mathematical expressionand then print the value of the expression include loop so that the user can perform many calculations (sayup to noteto quit earlythe user can make the program crash by typing bad expression or simply closing the window that the calculator program is running in you'll learn better ways of terminating interactive programs in later |
19,545 | writing simple programs |
19,546 | computing with numbers objectives to understand the concept of data types to be familiar with the basic numeric data types in python to understand the fundamental principles of how numbers are represented on computer to be able to use the python math library to understand the accumulator program pattern to be able to read and write programs that process numerical data numeric data types when computers were first developedthey were seen primarily as number crunchersand that is still an important application as you have seenproblems that involve mathematical formulas are easy to translate into python programs in this we'll take closer look at programs designed to perform numerical calculations the information that is stored and manipulated by computer programs is generically referred to as data different kinds of data will be stored and manipulated in different ways consider this program to calculate the value of loose changechange py program to calculate the value of some change in dollars def main()print("change counter"print(print("please enter the count of each coin type " |
19,547 | quarters eval(input("quarters")dimes eval(input("dimes")nickels eval(input("nickels")pennies eval(input("pennies")total quarters dimes nickels pennies print(print("the total value of your change is"totalmain(here is an example of the output change counter please enter the count of each coin type quarters dimes nickels pennies the total value of your change is this program actually manipulates two different kinds of numbers the values entered by the user ( are whole numbersthey don' have any fractional part the values of the coins are decimal representations of fractions inside the computerwhole numbers and numbers that have fractional components are stored differently technicallywe say that these are two different data types the data type of an object determines what values it can have and what operations can be performed on it whole numbers are represented using the integer data type (int for shortvalues of type int can be positive or negative whole numbers numbers that can have fractional parts are represented as floating point (or floatvalues so how do we tell whether number is an int or floata numeric literal that does not contain decimal point produces an int valuebut literal that has decimal point is represented by float (even if the fractional part is python provides special function called type that tells us the data type (or "class"of any value here is an interaction with the python interpreter showing the difference between int and float literalstype( type( type( myint - |
19,548 | type(myintmyfloat type(myfloatyou may be wondering why there are two different data types for numbers one reason has to do with program style values that represent counts can' be fractionalwe can' have quartersfor example using an int value tells the reader of program that the value can' be fraction another reason has to do with the efficiency of various operations the underlying algorithms that perform computer arithmetic are simplerand therefore fasterfor ints than the more general algorithms required for float values you should be warned that the float type only stores approximations to real numbers there is limit to the precisionor accuracyof the stored values since float values are not exactwhile ints always areyour general rule of thumb should beif you don' need fractional valuesuse an int operator *abs(/operation addition subtraction multiplication float division exponentiation absolute value integer division remainder table python built-in numeric operations value' data type determines what operations can be used on it as we have seenpython supports the usual mathematical operations on numbers table summarizes these operations actuallythis table is somewhat misleading since the two numeric data types have their own operations for examplei have listed single addition operationbut keep in mind that when addition is performed on floatsthe computer hardware performs floating point additionwhereas with ints the computer performs an integer addition python chooses the appropriate underlying operation (int or floatbased on the operands consider the following interaction with python |
19,549 | computing with numbers * * * abs( abs(- for the most partoperations on floats produce floatsand operations on ints produce ints most of the timewe don' even worry about what type of operation is being performedfor exampleinteger addition produces pretty much the same result as floating point additionand we can rely on python to do the right thing in the case of divisionhoweverthings get bit more interesting as the table showspython (as of version provides two different operators for division the usual symbol is used for "regulardivision and double slash /is used to indicate integer division the best way to get handle on the difference between these two is to try them out / / notice that the operator always returns float regular division often produces fractional resulteven though the operands may be ints python accommodates this by always returning floating point number are you surprised that the result of / has at the very endrememberfloating point values are always approximations this value is as close as python can get when representing as floating point number |
19,550 | to get division that returns an integer resultyou can use the integer division operation /integer division always produces an integer think of integer division as "gozinta the expression produces because three gozinta (goes intoten three times (with remainder of onewhile the result of integer division is always an integerthe data type of the result depends on the data type of the operands float integer-divided by float produces float with fractional component the last two interactions demonstrate the remainder operation the remainder of integer-dividing by is notice again that the data type of the result depends on the type of the operands depending on your math backgroundyou may not have used the integer division or remainder operations before the thing to keep in mind is that these two operations are closely related integer division tells you how many times one number goes into anotherand the remainder tells you how much is left over mathematically you could write the idea like thisa ( // )( )+( %bas an example applicationsuppose we calculated the value of our loose change in cents (rather than dollarsif have centsthen can find the number of whole dollars by computing // and the remaining change is % thusi must have total of three dollars and cents in change by the wayalthough pythonas of version treats regular division and integer division as two separate operatorsmany other computer languages (and earlier python versionsjust use to signify both when the operands are intsmeans integer divisionand when they are floatsit signifies regular division this is common source of errors for examplein our temperature conversion program the formula / celsius would not compute the proper resultsince / would evaluate to using integer division in these "old-fashionedlanguagesyou need to be careful to write this expression as celsius so that the proper form of division is usedyielding fractional result using the math library besides the operations listed in table python provides many other useful mathematical functions in special math library library is just module that contains some useful definitions our next program illustrates the use of this library to compute the roots of quadratic equations quadratic equation has the form ax bx such an equation has two solutions for the value of given by the quadratic formula- + ac let' write program that can find the solutions to quadratic equation the input to the program will be the values of the coefficients aband the outputs are the two values given by the quadratic formula here' program that does the job quadratic py program that computes the real roots of quadratic equation illustrates use of the math library |
19,551 | notethis program crashes if the equation has no real roots import math makes the math library available def main()print("this program finds the real solutions to quadratic"print(abc eval(input("please enter the coefficients (abc)")discroot math sqrt( croot (- discroot( aroot (- discroot( aprint(print("the solutions are:"root root main(this program makes use of the square root function sqrt from the math library module the line at the top of the programimport math tells python that we are using the math module importing module makes whatever is defined in it available to the program to compute xwe use math sqrt(xyou may recall this dot notation from this tells python to use the sqrt function that "livesin the math module in the quadratic program we calculate ac with the line discroot math sqrt( chere is how the program looks in actionthis program finds the real solutions to quadratic please enter the coefficients (abc) - the solutions are - this program is fine as long as the quadratics we try to solve have real solutions howeversome inputs will cause the program to crash here' another example runthis program finds the real solutions to quadratic please enter the coefficients (abc) |
19,552 | traceback (most recent call last)file "quadratic py"line in main(file "quadratic py"line in main discroot math sqrt( cvalueerrormath domain error the problem here is that ac and the sqrt function is unable to compute the square root of negative number python prints math domain error this is telling us that negative numbers are not in the domain of the sqrt function right nowwe don' have the tools to fix this problemso we will just have to assume that the user gives us solvable equations actuallyquadratic py did not need to use the math library we could have taken the square root using exponentiation *(can you see how?using math sqrt is somewhat more efficientand it allowed me to illustrate the use of the math library in generalif your program requires common mathematical functionthe math library is the first place to look table shows some of the other functions that are available in the math library python pi sin(xcos(xtan(xasin(xacos(xatan(xlog(xlog (xexp(xceil(xfloor(xmathematics sin cos tan arcsin arccos arctan ln log ex english an approximation of pi an approximation of the sine of the cosine of the tangent of the inverse of sine the inverse of cosine the inverse of tangent the natural (base elogarithm of the common (base logarithm of the exponential of the smallest whole number > the largest whole number < table some math library functions accumulating resultsfactorial suppose you have root beer sampler pack containing six different kinds of root beer drinking the various flavors in different orders might affect how good they taste if you wanted to try out every possible orderinghow many different orders would there beit turns out the answer is surprisingly large number do you know where this number comes fromthe value is the factorial of |
19,553 | computing with numbers in mathematicsfactorial is often denoted with an exclamation (!the factorial of whole number is defined as nn( )( ( this happens to be the number of distinct arrangements for items given six itemswe compute ( )( )( )( )( )( possible arrangements let' write program that will compute the factorial of number entered by the user the basic outline of our program follows an inputprocessoutput pattern input number to take factorial ofn compute factorial of nfact output fact obviouslythe tricky part here is in the second step how do we actually compute the factoriallet' try one by hand to get an idea for the process in computing the factorial of we first multiply ( then we take that result and do another multiplication ( this result is multiplied by three ( finallythis result is multiplied by ( according to the definitionwe then multiply this result by but that won' change the final value of now let' try to think about the algorithm more generally what is actually going on herewe are doing repeated multiplicationsand as we go alongwe keep track of the running product this is very common algorithmic pattern called an accumulator we build upor accumulatea final value piece by piece to accomplish this in programwe will use an accumulator variable and loop structure the general pattern looks like thisinitialize the accumulator variable loop until final result is reached update the value of accumulator variable realizing this is the pattern that solves the factorial problemwe just need to fill in the details we will be accumulating the factorial let' keep it in variable called fact each time through the loopwe need to multiply fact by one of the factors ( ) it looks like we should use for loop that iterates over this sequence of factors for exampleto compute the factorial of we need loop that works like thisfact for factor in [ , , , , , ]fact fact factor take minute to trace through the execution of this loop and convince yourself that it works when the loop body first executesfact has the value and factor is sothe new value of fact is the next time through the loopfactor will be and fact is updated to the pattern continues for each successive factor until the final result of has been accumulated the initial assignment of to fact before the loop is essential to get the loop started each time through the loop body (including the first)the current value of fact is used to compute the next value the initialization ensures that fact has value on the very first iteration whenever you |
19,554 | use the accumulator patternmake sure you include the proper initialization forgetting this is common mistake of beginning programmers of coursethere are many other ways we could have written this loop as you know from math classmultiplication is commutative and associativeso it really doesn' matter what order we do the multiplications in we could just as easily go the other direction you might also notice that including in the list of factors is unnecessarysince multiplication by does not change the result here is another version that computes the same resultfact for factor in [ , , , , ]fact fact factor unfortunatelyneither of these loops solves the original problem we have hand-coded the list of factors to compute the factorial of six what we really want is program that can compute the factorial of any given input we need some way to generate an appropriate sequence of factors from the value of luckilythis is quite easy to do using the python range function recall that range(nproduces sequence of numbers starting with and continuing up tobut not includingn there are other variations of range that can be used to produce different sequences with two parametersrange(start,nproduces sequence that starts with the value start and continues up tobut does not includen third version range(startnstepis like the two-parameter versionexcept that it uses step as the increment between numbers here are some exampleslist(range( )[ list(range( , )[ list(range( )[ given our input value we have couple of different range commands that produce an appropriate list of factors for computing the factorial of to generate them from smallest to largest ( la our second loop)we could use range( , + notice how used + as the second parametersince the range will go up to but not include this value we need the + to make sure that itself is included as the last factor another possibility is to generate the factors in the other direction ( la our first loopusing the three-parameter version of range and negative step to cause the counting to go backwardsrange( , ,- this one produces list starting with and counting down (step - tobut not including here then is one possible version of the factorial programfactorial py |
19,555 | program to compute the factorial of number illustrates for loop with an accumulator def main() eval(input("please enter whole number")fact for factor in range( , ,- )fact fact factor print("the factorial of" "is"factmain(of coursethere are numerous other ways this program could have been written have already mentioned changing the order of factors another possibility is to initialize fact to and then use factors starting at (as long as you might try out some of these variations and see which one you like best limitations of computer arithmetic it' sometimes suggested that the reason "!is used to represent factorial is because the function grows very rapidly for examplehere is what happens if we use our program to find the factorial of please enter whole number the factorial of is that' pretty big numberalthough recent versions of python have no difficulty with this calculationolder versions of python (and modern versions of other languages such as +and javawould not fare as well for examplehere' what happens in several runs of similar program written using java run please enter whole number the factorial is run please enter whole number the factorial is run please enter whole number the factorial is |
19,556 | this looks pretty goodwe know that quick check also confirms that unfortunatelyit turns out that it appears that the java program has given us an incorrect answerwhat is going on hereso fari have talked about numeric data types as representations of familiar numbers such as integers and decimals (fractionsit is important to keep in mindhoweverthat computer representations of numbers (the actual data typesdo not always behave exactly like the numbers that they stand for remember back in you learned that the computer' cpu can perform very basic operations such as adding or multiplying two numbersit would be more precise to say that the cpu can perform basic operations on the computer' internal representation of numbers the problem in this java program is that it is representing whole numbers using the computer' underlying int data type and relying on the computer' addition operation for ints unfortunatelythese machine ints are not exactly like mathematical integers there are infinitely many integersbut only finite range of ints inside the computerints are stored in fixed-sized binary representation to make sense of all thiswe need to look at what' going on at the hardware level computer memory is composed of electrical "switches,each of which can be in one of two possible statesbasically on or off each switch represents binary digit or bit of information one bit can encode two possibilitiesusually represented with the numerals (for offand (for ona sequence of bits can be used to represent more possibilities with two bitswe can represent four things bit bit three bits allow us to represent eight different values by adding zero or one to each of the four two-bit patterns bit bit bit you can see the pattern here each extra bit doubles the number of distinct patterns in generaln bits can represent different values the number of bits that particular computer uses to represent an int depends on the design of the cpu typical pcs today use or bits for bit cputhat means there are possible |
19,557 | computing with numbers values these values are centered at to represent range of positive and negative integers now to sothe range of integers that can be represented in bit int value is - the reason for the - on the high end is to account for the representation of in the top half of the range given this knowledgelet' try to make sense of what' happening in the java factorial example if the java program is relying on -bit int representationwhat' the largest number it can store python can give us quick answer ** - notice that this value (about billionlies between (about millionand (about billionthat means the java program is fine for calculating factorials up to but after that the representation "overflowsand the results are garbage now you know exactly why the simple java program can' compute of course that leaves us with another puzzle why does the modern python program seem to work quite well computing with large integers at firstyou might think that python uses the float data type to get us around the size limitation of the ints howeverit turns out that floats do not really solve this problem here is an example run of modified factorial program that uses floating point numbers please enter whole number the factorial of is + although this program runs just fineafter switching to floatwe no longer get an exact answer very large (or very smallfloating point value is printed out using exponentialor scientificnotation the + at the end means that the result is equal to you can think of the + at the end as marker that shows where the decimal point should be placed in this caseit must move places to the right to get the actual value howeverthere are only digits to the right of the decimalso we have "lostthe last digits rememberfloats are approximations using float allows us to represent much larger range of values than -bit intbut the amount of precision is still fixed in facta computer stores floating point numbers as pair of fixed-length (binaryintegers one integer represents the string of digits in the valueand the second represents the exponent value that keeps track of where the whole part ends and the fractional part begins fortunatelypython has better solution for largeexact values python int is not fixed sizebut expands to accommodate whatever value it holds the only limit is the amount of memory the computer has available to it when the value is smallpython can just use the computer' underlying int representation and operations when the value gets largerpython automatically converts to representation using more bits of coursein order to perform operations on larger numberspython has to break down the operations into smaller units that the computer hardware is able to handle sort of like the way you might do long division by hand these operations will not be as efficient (they require more steps)but they allow our python ints to grow to arbitrary size and that' what allows our simple factorial program to compute some whopping large results this is very cool feature of python |
19,558 | type conversions and rounding there are situations where value may need to be converted from one data type into another you already know that combining an int with an int (usuallyproduces an intand combining float with float creates another float but what happens if we write an expression that mixes an int with floatfor examplewhat should the value of be after this assignment statementx if this is floating point multiplicationthen the result should be the float value if an int multiplication is performedthe result is before reading ahead for the answertake minute to consider how you think python should handle this situation in order to make sense of the expression python must either change to and perform an int operation or convert to and perform floating point operation in generalconverting float to an int is dangerous stepbecause some information (the fractional partwill be lost on the other handan int can be safely turned into float just by adding fractional part of soin mixed-typed expressionspython will automatically convert ints to floats and perform floating point operations to produce float result sometimes we may want to perform type conversion ourselves this is called an explicit type conversion python provides the built-in functions int and float for these occasions here are some interactive examples that illustrate their behavior int( int( float( float( float(int( ) int(float( ) int(float( ) as you can seeconverting to an int simply discards the fractional part of floatthe value is truncatednot rounded if you want rounded resultyou could add to the value before using int()assuming the value is positive more general way of rounding off numbers is to use the built-in round function which rounds number to the nearest whole value round( |
19,559 | round( notice that calling round like this results in an int value so simple call to round is an alternative way of converting float to an int if you want to round float into another float valueyou can do that by supplying second parameter that specifies the number of digits you want after the decimal point here' little interaction playing around with the value of pi from the math libraryimport math math pi round(math pi round(math pi, print(round(math pi ) print(round(math pi, ) notice that when we round pi to two or three decimal placeswe do not get exactly two or three decimal places in the result rememberfloats are always approximationswe get something that' very close to what we requested howeverthe last two interactions show something interesting about the python print statement python is smart enough to know that we probably don' want to see all the digits in something like so it actually prints out the rounded form that means if you write program that rounds off value to two decimal places and you print out the valueyou'll end up seeing two decimal placesjust like you expect in we'll see how to get even finer control over how numbers appear when printed summary this has filled in some important details concerning programs that do numerical computations here is quick summary of some key conceptsthe way computer represents particular kind of information is called data type the data type of an object determines what values it can have and what operations it supports python has several different data types for representing numeric valuesincluding int and float whole numbers are generally represented using the int data type and fractional values are represented using floats all of the python numeric data types support standardbuilt-in |
19,560 | mathematical operations addition (+)subtraction (-)multiplication (*)division (/)integer division (//)remainder (%)exponentiation (**)and absolute value (abs( )additional mathematical functions are defined in the math library to use these functionsa program must first import the math library numerical results are often calculated by computing the sum or product of sequence of values the loop accumulator programming pattern is useful for this sort of calculation both ints and floats are represented on the underlying computer using fixed-length sequence of bits this imposes certain limits on these representations hardware ints must be in the range - ( on bit machine floats have finite amount of precision and cannot represent most numbers exactly python' int data type may be used to store whole numbers of arbitrary size int values are automatically converted to longer representations when they become too large for underlying hardware int calculations involving these long ints are less efficient than those that use only small ints python automatically converts numbers from one data type to another in certain situations for examplein mixed-type expression involving ints and floatspython first converts the ints into floats and then uses float arithmetic programs may also explicitly convert one data type into another using the functions float()int()and round( exercises review questions true/false information that is stored and manipulated by computers is called data since floating point numbers are extremely accuratethey should generally be used instead of ints operations like addition and subtraction are defined in the math library the number of possible rearrangements of items is equal to the sqrt function computes the squirt of number the int data type is identical to the mathematical concept of integer computers represent numbers using base representations |
19,561 | hardware float can represent larger range of values than hardware int an python int can represent indefinitely large numbers in python / produces the same result as multiple choice which of the following is not python data typeaint bfloat crational dstring which of the following is not built-in operationabcabs(dsqrt( in order to use functions in the math librarya program must include aa comment ba loop can operator dan import statement the value of is the most appropriate data type for storing the value of pi is aint bfloat cirrational dstring the number of distinct values that can be represented using bits is in mixed-type expression involving ints and floatspython will convert afloats to ints bints to strings cfloats and ints to strings dints to floats which of the following is not python type-conversion functionafloat bround cint dabs the pattern used to compute factorial is aaccumulator binputprocessoutput ccounted loop dplaid in modern pythonan int value that grows larger than the underlying hardware int acauses an overflow bconverts to float cbreaks the computer duses more memory discussion show the result of evaluating each expression be sure that the value is in the proper form to indicate its type (intlong intor floatif the expression is illegalexplain why ( ( |
19,562 | (cabs( * (dsqrt( ( ( * translate each of the following mathematical expressions into an equivalent python expression you may assume that the math library has been imported (via import math( ( )( (bn( - ( pr (dp (cos ) (sin ) - (ex - show the sequence of numbers that would be generated by each of the following range expressions (arange( (brange( (crange( (drange( - (erange( show the output that would be generated by each of the following program fragments (afor in range( )print( * (bfor in [ , , , , ]print( ":" ** print (cx for in range( yx)print(jend=""print( yprint "done(dans for in range( )ans ans * print(iprint (ans |
19,563 | what do you think will happen if you use negative number as the second parameter in the round functionfor examplewhat should be the result of round( - explain the rationale for your answer after you've written your answerconsult the python documentation or try out some examples to see what python actually does in this case what do you think will happen when the operands to the integer division or remainder operations are negativeconsider each of the following cases and try to predict the result then try them out in python hintrecall the magic formula ( // )( ( % ( - / ( - ( /- ( - ( - /- programming exercises write program to calculate the volume and surface area of sphere from its radiusgiven as input here are some formulas that might be usefulv / pr pr write program that calculates the cost per square inch of circular pizzagiven its diameter and price the formula for area is pr write program that determines the molecular weight of hydrocarbon based on the number of hydrogencarbonand oxygen atoms you should use the following weightsatom weight (grams mole write program that determines the distance to lightning strike based on the time elapsed between the flash and the sound of thunder the speed of sound is approximately ft/sec and mile is ft the konditorei coffee shop sells coffee at $ pound plus the cost of shipping each order ships for $ per pound $ fixed cost for overhead write program that calculates the cost of an order |
19,564 | two points in plane are specified using the coordinates ( , and ( , write program that calculates the slope of line through two (non-verticalpoints entered by the user slope write program that accepts two points (see previous problemand determines the distance between them distance ( ) ( ) the gregorian epact is the number of days between january st and the previous new moon this value is used to figure out the date of easter it is calculated by these formulas (using int arithmetic) year// epact ( ( // (( )// (year% ))% write program that prompts the user for -digit year and then outputs the value of the epact write program to calculate the area of triangle given the length of its three sides aband using these formulasa+ + aq ( )( )( write program to determine the length of ladder required to reach given height when leaned against house the height and angle of the ladder are given as inputs to compute length use height length sin angle notethe angle must be in radians prompt for an angle in degrees and use this formula to convertp degrees radians write program to find the sum of the first natural numberswhere the value of is provided by the user write program to find the sum of the cubes of the first natural numbers where the value of is provided by the user write program to sum series of numbers entered by the user the program should first prompt the user for how many numbers are to be summed it should then input each of the numbers and print total sum |
19,565 | write program that finds the average of series of numbers entered by the user as in the previous problemthe program will first ask the user how many numbers there are notethe average should always be floateven if the user inputs are all ints write program that approximates the value of by summing the terms of this series / / / / / / the program should prompt the user for nthe number of terms to sumand then output the sum of the first terms of this series have your program subtract the approximation from the value of math pi to see how accurate it is fibonacci sequence is sequence of numbers where each successive number is the sum of the previous two the classic fibonacci sequence begins write program that computes the nth fibonacci number where is value input by the user for exampleif then the result is you have seen that the math library contains function that computes the square root of numbers in this exerciseyou are to write your own algorithm for computing square roots one way to solve this problem is to use guess-and-check approach you first guess what the square root might be and then see how close your guess is you can use this information to make another guess and continue guessing until you have found the square root (or close approximation to itone particularly good way of making guesses is to use newton' method suppose is the number we want the root of and guess is the current guessed answer the guess can be improved by using guessguess as the next guess write program that implements newton' method the program should prompt the user for the value to find the square root of (xand the number of times to improve the guess starting with guess value of / your program should loop the specified number of times applying newton' method and report the final value of guess you should also subtract your estimate from the value of math sqrt(xto show how close it is |
19,566 | objects and graphics objectives to understand the concept of objects and how they can be used to simplify programming to be familiar with the various objects available in the graphics library to be able to create objects in programs and call appropriate methods to perform graphical computations to understand the fundamental concepts of computer graphicsespecially the role of coordinate systems and coordinate transformations to understand how to work with both mouse and text-based input in graphical programming context to be able to write simple interactive graphics programs using the graphics library overview so far we have been writing programs that use the built-in python data types for numbers and strings we saw that each data type could represent certain set of valuesand each had set of associated operations basicallywe viewed the data as passive entities that were manipulated and combined via active operations this is traditional way to view computation to build complex systemshoweverit helps to take richer view of the relationship between data and operations most modern computer programs are built using an object-oriented (ooapproach object orientation is not easily defined it encompasses number of principles for designing and implementing softwareprinciples that we will return to numerous times throughout the course of this book this provides basic introduction to object concepts by way of some computer graphics |
19,567 | graphical programming is lot of fun and provides great vehicle for learning about objects in the processyou will also learn the principles of computer graphics that underlie many modern computer applications most of the applications that you are familiar with probably have so-called graphical user interface (guithat provides visual elements like windowsicons (representative pictures)buttonsand menus interactive graphics programming can be very complicatedentire textbooks are devoted to the intricacies of graphics and graphical interfaces industrial-strength gui applications are usually developed using dedicated graphics programming framework python comes with its own standard gui module called tkinter as gui frameworks gotkinter is one of the simplest to useand python is great language for developing real-world guis stillat this point in your programming careerit would be challenge to learn the intricacies of any gui frameworkand doing so would not contribute much to the main objectives of this which are to introduce you to objects and the fundamental principles of computer graphics to make learning these basic concepts easierwe will use graphics library (graphics pyspecifically written for use with this textbook this library is wrapper around tkinter that makes it more suitable for beginning programmers it is freely available as python module file and you are welcome to use it as you see fit eventuallyyou may want to study the code for the library itself as stepping stone to learning how to program directly in tkinter the object of objects the basic idea of object-oriented development is to view complex system as the interaction of simpler objects the word objects is being used here in specific technical sense part of the challenge of oo programming is figuring out the vocabulary you can think of an oo object as sort of active data type that combines both data and operations to put it simplyobjects know stuff (they contain data)and they can do stuff (they have operationsobjects interact by sending each other messages message is simply request for an object to perform one of its operations consider simple example suppose we want to develop data processing system for college or university we will need to keep track of considerable information for starterswe must keep records on the students who attend the school each student could be represented in the program as an object student object would contain certain data such as nameid numbercourses takencampus addresshome addressgpaetc each student object would also be able to respond to certain requests for exampleto send out mailingwe would need to print an address for each student this task might be handled by printcampusaddress operation when particular student object is sent the printcampusaddress messageit prints out its own address to print out all the addressesa program would loop through the collection of student objects and send each one in turn the printcampusaddress message objects may refer to other objects in our exampleeach course in the college might also be represented by an object course objects would know things such as who the instructor iswhat students are in the coursewhat the prerequisites areand when and where the course meets one see appendix for information on how to obtain the graphics library and other supporting materials for this book |
19,568 | example operation might be addstudentwhich causes student to be enrolled in the course the student being enrolled would be represented by the appropriate student object instructors would be another kind of objectas well as roomsand even times you can see how successive refinement of these ideas could lead to rather sophisticated model of the information structure of the college as beginning programmeryou're probably not yet ready to tackle college information system for nowwe'll study objects in the context of some simple graphics programming simple graphics programming in order to run the graphical programs and examples in this (and the rest of the book)you will need copy of the file graphics py that is supplied with the supplemental materials using the graphics library is as easy as placing copy of the graphics py file in the same folder as your graphics program(salternativelyyou can place it in system directory where other python libraries are stored so that it can be used from any folder on the system the graphics library makes it easy to experiment with graphics interactively and write simple graphics programs as you doyou will be learning principles of object-oriented programming and computer graphics that can be applied in more sophisticated graphical programming environments the details of the graphics module will be explored in later sections here we'll concentrate on basic hands-on introduction to whet your appetite as usualthe best way to start learning new concepts is to roll up your sleeves and try out some examples the first step is to import the graphics module assuming you have placed graphics py in an appropriate placeyou can import the graphics commands into an interactive python session import graphics next we need to create place on the screen where the graphics will appear that place is graphics window or graphwinwhich is provided by the graphics module win graphics graphwin(notice the use of dot notation to invoke the graphwin function that "lives inthe graphics library this is analogous to when we used math sqrt(xto invoke the square root function from the math library module the graphwin(function creates new window on the screen the window will have the title "graphics window the graphwin may overlap your python interpreter windowso you might have to resize or move the python window to make both fully visible figure shows an example screen view the graphwin is an objectand we have assigned it to the variable called win we can now manipulate the window object through this variable for examplewhen we are finished with windowwe can destroy it this is done by issuing the close command win close(typing this command causes the window to vanish from the screen notice that we are again using the dot notation herebut now we are using it with variable namenot module nameon the left side of the dot recall that win was earlier assigned an object |
19,569 | figure screen shot with python window and graphwin of type graphwin one of the things graphwin object can do is to close itself you can think of this command as invoking the close operation that is associated with this particular window the result is that the window disappears from the screen we will be working with quite few commands from the graphics libraryand it gets tedious having to type the graphics notation every time we use one python has an alternative form of import that can help out from graphics import the from statement allows you to load specific definitions from library module you can either list the names of definitions to be imported or use an asteriskas shownto import everything defined in the module the imported commands become directly available without having to preface them with the module name after doing this importwe can create graphwin more simply win graphwin(all of the rest of the graphics examples will assume that the entire graphics module has been imported using from let' try our hand at some drawing graphics window is actually collection of tiny points called pixels (short for picture elementsby controlling the color of each pixelwe control what is displayed in the window by defaulta graphwin is pixels tall and pixels wide that means there are , pixels in the graphwin drawing picture by assigning color to each individual pixel would be daunting challenge insteadwe will rely on library of graphical objects each type of object does its own bookkeeping and knows how to draw itself into graphwin |
19,570 | the simplest object in the graphics module is point in geometrya point is location in space point is located by reference to coordinate system our graphics object point is similarit can represent location in graphwin we define point by supplying and coordinates (xythe value represents the horizontal location of the pointand the value represents the vertical traditionallygraphics programmers locate the point ( in the upper-left corner of the window thus values increase from left to rightand values increase from top to bottom in the default graphwinthe lower-right corner has the coordinates ( drawing point sets the color of the corresponding pixel in the graphwin the default color for drawing is black here is sample interaction with python illustrating the use of pointsp point( , getx( gety( win graphwin( draw(winp point( , draw(winthe first line creates point located at ( after the point has been createdits coordinate values can be accessed by the operations getx and gety point is drawn into window using the draw operation in this exampletwo different point objects ( and are created and drawn into the graphwin called win figure shows the resulting graphical output figure graphics window with two points drawn in addition to pointsthe graphics library contains commands for drawing linescirclesrectanglesovalspolygons and text each of these objects is created and drawn in similar fashion here is sample interaction to draw various shapes into graphwin |
19,571 | objects and graphics ###open graphics window win graphwin('shapes'###draw red circle centered at point ( , with radius center point( , circ circle(center circ setfill('red'circ draw(win###put textual label in the center of the circle label text(center"red circle"label draw(win###draw square using rectangle object rect rectangle(point( , )point( , )rect draw(win###draw line segment using line object line line(point( , )point( )line draw(win###draw an oval using the oval object oval oval(point( , )point( , )oval draw(wintry to figure out what each of these statements does if you type them in as shownthe final result will look like figure figure various shapes from the graphics module |
19,572 | using graphical objects some of the examples in the above interactions may look bit strange to you to really understand the graphics modulewe need to take an object-oriented point of view rememberobjects combine data with operations computation is performed by asking an object to carry out one of its operations in order to make use of objectsyou need to know how to create them and how to request operations in the interactive examples abovewe manipulated several different kinds of objectsgraphwinpointcircleovallinetextand rectangle these are examples of classes every object is an instance of some classand the class describes the properties the instance will have borrowing biological metaphorwhen we say that fido is dogwe are actually saying that fido is specific individual in the larger class of all dogs in oo terminologyfido is an instance of the dog class because fido is an instance of this classwe expect certain things fido has four legsa taila coldwet nose and he barks if rex is dogwe expect that he will have similar propertieseven though fido and rex may differ in specific details such as size or color the same ideas hold for our computational objects we can create two separate instances of pointsay and each of these points has an and valueand they both support the same set of operations like getx and draw these properties hold because the objects are points howeverdifferent instances can vary in specific details such as the values of their coordinates to create new instance of classwe use special operation called constructor call to constructor is an expression that creates brand new object the general form is as follows(here is the name of the class that we want to create new instance ofe circle or point the expressions in the parentheses are any parameters that are required to initialize the object the number and type of the parameters depends on the class point requires two numeric valueswhile graphwin can be constructed without any parameters oftena constructor is used on the right side of an assignment statementand the resulting object is immediately assigned to variable on the left side that is then used to manipulate the object to take concrete examplelet' look at what happens when we create graphical point here is constructor statement from the interactive example above point( , the constructor for the point class requires two parameters giving the and coordinates for the new point these values are stored as instance variables inside of the object in this casepython creates an instance of point having an value of and value of the resulting point is then assigned to the variable conceptual diagram of the result is shown in figure note thatin this diagram as well as similar ones later ononly the most salient details are shown points also contain other information such as their color and which window (if anythey are drawn in most of this information is set to default values when the point is created to perform an operation on an objectwe send the object message the set of messages that an object responds to are called the methods of the object you can think of methods as functions that live inside of the object method is invoked using dot-notation |
19,573 | point px figure conceptual picture of the result of point( , the variable refers to freshly created point having the given coordinates (the number and type of the parameters is determined by the method being used some methods require no parameters at all you can find numerous examples of method invocation in the interactive examples above as examples of parameterless methodsconsider these two expressionsp getx( gety(the getx and gety methods return the and values of pointrespectively methods such as these are sometimes called accessorsbecause they allow us to access information from the instance variables of the object other methods change the values of an object' instance variableshence changing the state of the object all of the graphical objects have move method here is specificationmove(dxdy)moves the object dx units in the direction and dy units in the direction to move the point to the right unitswe could use this statement move( , this changes the instance variable of by adding units if the point is currently drawn in graphwinmove will also take care of erasing the old image and drawing it in its new position methods that change the state of an object are sometimes called mutators the move method must be supplied with two simple numeric parameters indicating the distance to move the object along each dimension some methods require parameters that are themselves complex objects for exampledrawing circle into graphwin involves two objects let' examine sequence of commands that does this circ circle(point( , ) win graphwin(circ draw(win |
19,574 | the first line creates circle with center located at the point ( and radius of notice that we used the point constructor to create location for the first parameter to the circle constructor the second line creates graphwin do you see what is happening in the third linethis is request for the circle object circ to draw itself into the graphwin object win the visible effect of this statement is circle in the graphwin centered at ( and having radius of behind the scenesa lot more is happening rememberthe draw method lives inside the circ object using information about the center and radius of the circle from the instance variablesthe draw method issues an appropriate sequence of low-level drawing commands ( sequence of method invocationsto the graphwin conceptual picture of the interactions among the pointcircle and graphwin objects is shown in figure fortunatelywe don' usually have to worry about these kinds of detailsthey're all taken care of by the graphical objects we just create objectscall the appropriate methodsand let them do the work that' the power of object-oriented programming circle circpoint centerradiusdraw low-level drawing commands graphwin winfigure object interactions to draw circle there is one subtle "gotchathat you need to keep in mind when using objects it is possible for two different variables to refer to exactly the same objectchanges made to the object through one variable will also be visible to the other suppose we are trying to write sequence of code that draws smiley face we want to create two eyes that are units apart here is sequence of code intended to draw the eyes #incorrect way to create two circles lefteye circle(point( ) lefteye setfill('yellow'lefteye setoutline('red' |
19,575 | righteye lefteye righteye move( , the basic idea is to create the left eye and then copy that into right eye which is then moved over units this doesn' work the problem here is that only one circle object is created the assignment righteye lefteye simply makes righteye refer to the very same circle as lefteye figure shows the situation when the circle is moved in the last line of codeboth righteye and lefteye refer to it in its new location on the right side this situation where two variables refer to the same object is called aliasingand it can sometimes produce rather unexpected results lefteyecircle point centerradius righteyefigure variables lefteye and righteye are aliases one solution to this problem would be to create separate circle for each eye # correct way to create two circles lefteye circle(point( ) lefteye setfill('yellow'lefteye setoutline('red'righteye circle(point( ) righteye setfill('yellow'righteye setoutline('red'this will certainly workbut it' cumbersome we had to write duplicated code for the two eyes that' easy to do using "cut and pasteapproachbut it' not very elegant if we decide to change the appearance of the eyeswe will have to be sure to make the changes in two places the graphics library provides better solutionall graphical objects support clone method that makes copy of the object using clonewe can rescue the original approach #correct way to create two circlesusing clone lefteye circle(point( ) lefteye setfill('yellow'lefteye setoutline('red' |
19,576 | righteye lefteye clone(righteye is an exact copy of the left righteye move( , strategic use of cloning can make some graphics tasks much easier graphing future value now that you have some idea of how to use objects from the graphics modulewe're ready to try some real graphics programming one of the most important uses of graphics is providing visual representation of data they say picture is worth thousand wordsit is almost certainly better than thousand numbers just about any program that manipulates numeric data can be improved with bit of graphical output remember the program in that computed the future value of ten year investmentlet' try our hand at creating graphical summary programming with graphics requires careful planning you'll probably want pencil and paper handy to draw some diagrams and scratch out calculations as we go along as usualwe begin by considering the specification of exactly what the program will do the original program futval py had two inputsthe amount of money to be invested and the annualized rate of interest using these inputsthe program calculated the change in principal year by year for ten years using the formula principal principal( aprit then printed out the final value of the principal in the graphical versionthe output will be ten-year bar graph where the height of successive bars represents the value of the principal in successive years let' use concrete example for illustration suppose we invest $ at interest this table shows the growth of the investment over ten-year periodyears value $ , $ , $ , $ , $ , $ , $ , $ , $ , $ , $ , our program will display this information in bar graph figure shows the data in graphical form the graph actually contains eleven bars the first bar shows the original value of the principal for referencelet' number these bars according to the number of years of interest accrued - here is rough design for the program |
19,577 | objects and graphics figure bar graph showing growth of $ , at interest print an introduction get value of principal and apr from user create graphwin draw scale labels on left side of window draw bar at position with height corresponding to principal for successive years through calculate principal principal ( aprdraw bar for this year having height corresponding to principal wait for user to press enter the pause created by the last step is necessary to keep the graphics window displayed so that we can interpret the results without such pausethe program would end and the graphwin would vanish with it while this design gives us the broad brush strokes for our algorithmthere are some very important details that have been glossed over we must decide exactly how big the graphics window will be and how we will position the objects that appear in this window for examplewhat does it mean to drawsaya bar for year five with height corresponding to $ , let' start with the size of the graphwin recall that the size of window is given in terms of the number of pixels in each dimension computer screens are also measured in terms of pixels the number of pixels or resolution of the screen is determined by the monitor and graphics card in the computer you use the lowest resolution screen you are likely to encounter on personal computer these days is so-called extended vga screen that is pixels most screens are considerably larger our default pixel window will probably seem bit small let' make the graphwin that will make it about / the size of small screen given this analysiswe can flesh out bit of our design the third line of the design should now |
19,578 | readcreate graphwin titled ''investment growth chart'you may be wondering how this will translate into python code you have already seen that the graphwin constructor allows an optional parameter to specify the title of the window you may also supply width and height parameters to control the size of the window thusthe command to create the output window will bewin graphwin("investment growth chart" next we turn to the problem of printing labels along the left edge of our window to simplify the problemwe will assume the graph is always scaled to maximum of $ , with the five labels " kto " kas shown in the example window the question is how should the labels be drawnwe will need some text objects when creating textwe specify the anchor point (the point the text is centered onand the string to use as the label the label strings are easy our longest label is five charactersand the labels should all line up on the right side of columnso the shorter strings will be padded on the left with spaces the placement of the labels is chosen with bit of calculation and some trial and error playing with some interactive examplesit seems that string of length five looks nicely positioned in the horizontal direction placing the center pixels in from the left edge this leaves just bit of white space at the margin in the vertical directionwe have just over pixels to work with simple scaling would be to have pixels represent $ , that means our five labels should be spaced pixels apart using pixels for the range - , leaves pixels to split between the top and bottom margins we might want to leave little more margin at the top to accommodate values that grow beyond $ , little experimentation suggests that putting the klabel pixels from the bottom (position seems to look nice elaborating our algorithm to include these detailsthe single step draw scale labels on left side of window becomes sequence of steps draw label kat ( draw label kat ( draw label kat ( draw label kat ( draw label " kat ( the next step in the original design calls for drawing the bar that corresponds to the initial amount of the principal it is easy to see where the lower left corner of this bar should be the value of $ is located vertically at pixel and the labels are centered pixels in from the left edge adding another pixels gets us to the right edge of the labels thus the lower left corner of the th bar should be at location ( |
19,579 | now we just need to figure out where the opposite (upper rightcorner of the bar should be so that we can draw an appropriate rectangle in the vertical directionthe height of the bar is determined by the value of principal in drawing the scalewe determined that pixels is equal to $ , this means that we have / pixels to the dollar this tells usfor examplethat principal of $ , should produce bar of height pixels in generalthe position of the upper-right corner will be given by -(principal)( (remember that is the pointand the coordinates decrease going uphow wide should the bar bethe window is pixels widebut pixels are eaten up by the labels on the left that leaves us with pixels for bars / let' just make each bar pixelsthat will give us bit of margin on the right side sothe right edge of our first bar will be at position we can now fill in the details for drawing the first bar into our algorithm draw rectangle from ( to ( principal at this pointwe have made all the major decisions and calculations required to finish out the problem all that remains is to percolate these details into the rest of the algorithm figure shows the general layout of the window with some of the dimensions we have chosen ( , ( , ( , ( , figure position of elements in future value bar graph let' figure out where the lower-left corner of each bar is going to be located we chose bar width of so the bar for each successive year will start pixels farther right than the previous year we can use variable year to represent the year number and calculate the coordinate of the lower left corner as (year)( (the + leaves space on the left edge for the labels of coursethe coordinate of this point is still (the bottom of the graphto find the upper-right corner of barwe add (the width of the barto the value of the lower-left corner the value of the upper right corner is determined from the (updatedvalue of principal exactly as we determined it for the first bar here is the refined algorithm |
19,580 | for year running from value of up through calculate principal principal ( aprcalculate xll year calculate height principal draw rectangle from (xll to (xll+ heightthe variable xll stands for lower left--the value of the lower left corner of the bar putting all of this together produces the detailed algorithm shown belowprint an introduction get value of principal and apr from user create graphwin titled ''investment growth chart'draw label kat ( draw label kat ( draw label kat ( draw label kat ( draw label " kat ( draw rectangle from ( to ( principal for year running from value of up through calculate principal principal ( aprcalculate xll year draw rectangle from (xll to (xll+ principal wait for user to press enter whewthat was lot of workbut we are finally ready to translate this algorithm into actual python code the translation is straightforward using objects from the graphics module here' the programfutval_graph py from graphics import def main()introduction print("this program plots the growth of -year investment "get principal and interest rate principal eval(input("enter the initial principal")apr eval(input("enter the annualized interest rate")create graphics window with labels on left edge win graphwin("investment growth chart" win setbackground("white"text(point( ) 'draw(win |
19,581 | text(point( ) 'draw(wintext(point( ) 'draw(wintext(point( ) 'draw(wintext(point( )' 'draw(windraw bar for initial principal height principal bar rectangle(point( )point( -height)bar setfill("green"bar setwidth( bar draw(windraw bars for successive years for year in range( , )calculate value for the next year principal principal ( aprdraw bar for this value xll year height principal bar rectangle(point(xll )point(xll+ -height)bar setfill("green"bar setwidth( bar draw(wininput("press to quit"win close(main(if you study this program carefullyyou will see that added number of features to spruce it up bit all graphical objects support methods for changing color have set the background color of the window to white (by default it' graywin setbackground("white" have also changed the color of the bar object the following line asks the bar to color its interior green (because it' moneyyou know)bar setfill("green"you can also change the color of shape' outline using the setoutline method in this casei have chosen to leave the outline the default black so that the bars stand out from each other to enhance this effectthis code makes the outline wider (two pixels instead of the default one |
19,582 | bar setwidth( you might also have noted the economy of notation in drawing the labels since we don' ever change the labelsassigning them to variable is unnecessary we can just create text objecttell it to draw itselfand be done with it here is an exampletext(point( , ) 'draw(winfinallytake close look at the use of the year variable in the loop for year in range( , )the expression range( , produces sequence of ints - the loop index variable year marches through this sequence on successive iterations of the loop sothe first time through year is then then etc up to the value of year is then used to compute the proper position of the lower left corner of each bar xll year hope you are starting to get the hang of graphics programming it' bit strenuousbut very addictive choosing coordinates the lion' share of the work in designing the futval_graph program was in determining the precise coordinates where things would be placed on the screen most graphics programming problems require some sort of coordinate transformation to change values from real-world problem into the window coordinates that get mapped onto the computer screen in our examplethe problem domain called for values representing the year ( - and values representing monetary amounts ($ -$ , we had to transform these values to be represented in window it' nice to work through an example or two to see how this transformation happensbut it makes for tedious programming coordinate transformation is an integral and well-studied component of computer graphics it doesn' take too much mathematical savvy to see that the transformation process always follows the same general pattern anything that follows pattern can be done automatically in order to save you the trouble of having to explicitly convert back and forth between coordinate systemsthe graphics module provides simple mechanism to do it for you when you create graphwin you can specify coordinate system for the window using the setcoords method the method requires four parameters specifying the coordinates of the lower-left and upper-right cornersrespectively you can then use this coordinate system to place graphical objects in the window to take simple examplesuppose we just want to divide the window into nine equal squarestic-tac-toe fashion this could be done without too much trouble using the default windowbut it would require bit of arithmetic the problem becomes trivial if we first change the coordinates of the window to run from to in both dimensions |
19,583 | create default window win graphwin("tic-tac-toe"set coordinates to go from ( , in the lower left to ( , in the upper right win setcoords( draw vertical lines line(point( , )point( , )draw(winline(point( , )point( , )draw(windraw horizontal lines line(point( , )point( , )draw(winline(point( , )point( , )draw(winanother benefit of this approach is that the size of the window can be changed by simply changing the dimensions used when the window is created ( win graphwin("tic-tac-toe" )because the same coordinates span the window (due to setcoordsthe objects will scale appropriately to the new window size using "rawwindow coordinates would require changes in the definitions of the lines we can apply this idea to simplify our graphing future value program basicallywe want our graphics window to go from through (representing yearsin the dimension and from to , (representing dollarsin the dimension we could create just such window like this win graphwin("investment growth chart" win setcoords( then creating bar for any values of year and principal would be simple each bar starts at the given year and baseline of and grows to the next year and height equal to principal bar rectangle(point(year )point(year+ principal)there is small problem with this scheme can you see what have forgottenthe eleven bars will fill the entire windowwe haven' left any room for labels or margins around the edges this is easily fixed by expanding the coordinates of the window slightly since our bars start at we can locate the left side labels at - we can add bit of white space around the graph by expanding the coordinates slightly beyond that required for our graph little experimentation leads to this window definitionwin graphwin("investment growth chart" win setcoords(- ,- here is the program againusing the alternative coordinate systemfutval_graph py |
19,584 | from graphics import def main()introduction print("this program plots the growth of -year investment "get principal and interest rate principal eval(input("enter the initial principal")apr eval(input("enter the annualized interest rate")create graphics window with labels on left edge win graphwin("investment growth chart" win setbackground("white"win setcoords(- ,- text(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- )' 'draw(windraw bar for initial principal bar rectangle(point( )point( principal)bar setfill("green"bar setwidth( bar draw(windraw bar for each subsequent year for year in range( )principal principal ( aprbar rectangle(point(year )point(year+ principal)bar setfill("green"bar setwidth( bar draw(wininput("press to quit "win close(main(notice how the cumbersome coordinate calculations have been eliminated this version also makes it easy to change the size of the graphwin changing the window size to produces largerbut correctly drawn bar graph in the original programall of the calculations would have |
19,585 | objects and graphics to be redone to accommodate the new scaling factors in the larger window obviouslythe second version of our program is much easier to develop and understand when you are doing graphics programminggive some consideration to choosing coordinate system that will make your task as simple as possible interactive graphics graphical interfaces can be used for input as well as output in gui environmentusers typically interact with their applications by clicking on buttonschoosing items from menusand typing information into on-screen text boxes these applications use technique called event-driven programming basicallythe program draws set of interface elements (often called widgetson the screenand then waits for the user to do something when the user moves the mouseclicks button or types key on the keyboardthis generates an event basicallyan event is an object that encapsulates data about what just happened the event object is then sent off to an appropriate part of the program to be processed for examplea click on button might produce button event this event would be passed to the button handling codewhich would then perform the appropriate action corresponding to that button event-driven programming can be tricky for novice programmerssince it' hard to figure out "who' in chargeat any given moment the graphics module hides the underlying event-handling mechanisms and provides two simple ways of getting user input in graphwin getting mouse clicks we can get graphical information from the user via the getmouse method of the graphwin class when getmouse is invoked on graphwinthe program pauses and waits for the user to click the mouse somewhere in the graphics window the spot where the user clicks is returned to the program as point here is bit of code that reports the coordinates of ten successive mouse clicksclick py from graphics import def main()win graphwin("click me!"for in range( ) win getmouse(print("you clicked at:" getx() gety()main(the value returned by getmouse(is ready-made point we can use it like any other point using accessors such as getx and gety or other methods such as draw and move |
19,586 | here is an example of an interactive program that allows the user to draw triangle by clicking on three points in graphics window this example is completely graphicalmaking use of text objects as prompts no interaction with python text window is required if you are programming in microsoft windows environmentyou can name this program using pyw extension then when the program is runit will not even display the python shell window triangle pyw from graphics import def main()win graphwin("draw triangle"win setcoords( message text(point( )"click on three points"message draw(winget and draw three vertices of triangle win getmouse( draw(winp win getmouse( draw(winp win getmouse( draw(winuse polygon object to draw the triangle triangle polygon( , , triangle setfill("peachpuff"triangle setoutline("cyan"triangle draw(winwait for another click to exit message settext("click anywhere to quit "win getmouse(main(the three-click triangle illustrates couple new features of the graphics module there is no triangle classhowever there is general class polygon that can be used for any multi-sidedclosed shape the constructor for polygon accepts any number of points and creates polygon by using line segments to connect the points in the order given and to connect the last point back to the first triangle is just three-sided polygon once we have three points and creating the triangle is snap triangle polygon( |
19,587 | you should also study how the text object is used to provide prompts single text object is created and drawn near the beginning of the program message text(point( )"click on three points"message draw(winto change the promptwe don' need to create new text objectwe can just change the text that is displayed this is done near the end of the program with the settext method message settext("click anywhere to quit "as you can seethe getmouse method of graphwin provides simple way of interacting with the user in graphics-oriented program handling textual input in the triangle exampleall of the input was provided through mouse clicks the graphics module also includes simple entry object that can be used to get keyboard input in graphwin an entry object draws box on the screen that can contain text it understands settext and gettext methods just like the text object does the difference is that the contents of an entry can be edited by the user here' version of the temperature conversion program from with graphical user interfaceconvert_gui pyw program to convert celsius to fahrenheit using simple graphical interface from graphics import def main()win graphwin("celsius converter" win setcoords( draw the interface text(point( , )celsius temperature:"draw(wintext(point( , )"fahrenheit temperature:"draw(wininput entry(point( , ) input settext(" "input draw(winoutput text(point( , ),""output draw(winbutton text(point( , ),"convert it"button draw(winrectangle(point( , )point( , )draw(win |
19,588 | wait for mouse click win getmouse(convert input celsius eval(input gettext()fahrenheit celsius display output and change button output settext(fahrenheitbutton settext("quit"wait for click and then quit win getmouse(win close(main(when runthis produces window with an entry box for typing in celsius temperature and "buttonfor doing the conversion the button is just for show the program actually just pauses for mouse click anywhere in the window figure shows how the window looks when the program starts figure initial screen for graphical temperature converter initiallythe input entry box is set to contain the value the user can delete this value and type in another temperature the program pauses until the user clicks the mouse notice that the point where the user clicks is not even savedthe getmouse method is just used to pause the program until the user has chance to enter value in the input box |
19,589 | the program then processes the input in four steps firstthe text in the input box is converted into number (via evalthis number is then converted to degrees fahrenheit finallythe resulting number is displayed in the output text area although fahrenheit is an int valuethe settext method automatically converts it to string so that it can be displayed in the output text box figure shows how the window looks after the user has typed an input and clicked the mouse notice that the converted temperature shows up in the output areaand the label on the button has changed to "quitto show that clicking again will exit the program this example could figure graphical temperature converter after user input be made much prettier using some of the options in the graphics library for changing the colorssizes and line widths of the various widgets the code for the program is deliberately spartan to illustrate just the essential elements of gui design although the basic tools getmouse and entry do not provide full-fledged gui environmentwe will see in later how these simple mechanisms can support surprisingly rich interactions graphics module reference the examples in this have touched on most of the elements in the graphics module this section provides complete reference to the objects and functions provided in the graphics library the set of objects and functions that are provided by module is sometimes called an applications programming interface or api experienced programmers study apis to learn about new libraries you should probably read this section over once to see what the graphics library has to offer after thatyou will probably want to refer back to this section often when you are writing your own graphical programs |
19,590 | graphwin objects graphwin object represents window on the screen where graphical images may be drawn program may define any number of graphwins graphwin understands the following methodsgraphwin(titlewidthheightconstructs new graphics window for drawing on the screen the parameters are optionalthe default title is "graphics window,and the default size is plot(xycolordraws the pixel at (xyin the window color is optionalblack is the default plotpixel(xycolordraws the pixel at the "rawposition (xyignoring any coordinate transformations set up by setcoords setbackground(colorsets the window background to the given color the initial background is gray see section for information on specifying colors close(closes the on-screen window getmouse(pauses for the user to click mouse in the window and returns where the mouse was clicked as point object setcoords(xllyllxuryursets the coordinate system of the window the lower left corner is (xllylland the upper right corner is (xuryurall subsequent drawing will be done with respect to the altered coordinate system (except for plotpixelgraphics objects the module provides the following classes of drawable objectspointlinecircleovalrectanglepolygonand text all objects are initially created unfilled with black outline all graphics objects support the following generic set of methodssetfill(colorsets the interior of the object to the given color setoutline(colorsets the outline of the object to the given color setwidth(pixelssets the width of the outline of the object to this many pixels (does not work for point draw(agraphwindraws the object into the given graphwin undraw(undraws the object from graphics window this produces an error if the object is not currently drawn move(dx,dymoves the object dx units in the direction and dy units in the direction if the object is currently drawnthe image is adjusted to the new position clone(returns duplicate of the object clones are always created in an undrawn state other than thatthey are identical to the cloned object |
19,591 | objects and graphics point methods point( ,yconstructs point having the given coordinates getx(returns the coordinate of point gety(returns the coordinate of point line methods line(point point constructs line segment from point to point setarrow(stringsets the arrowhead status of line arrows may be drawn at either the first pointthe last pointor both possible values of string are 'first''last''both'and 'nonethe default setting is 'nonegetcenter(returns clone of the midpoint of the line segment getp ()getp (returns clone of the corresponding endpoint of the segment circle methods circle(centerpointradiusconstructs circle with given center point and radius getcenter(returns clone of the center point of the circle getradius(returns the radius of the circle getp ()getp (returns clone of the corresponding corner of the circle' bounding box these are opposite corner points of square that circumscribes the circle rectangle methods rectangle(point point constructs rectangle having opposite corners at point and point getcenter(returns clone of the center point of the rectangle getp ()getp (returns clone of corner points originally used to construct the rectangle oval methods oval(point point constructs an oval in the bounding box determined by point and point getcenter(returns clone of the point at the center of the oval getp ()getp (returns clone of the corresponding point used to construct the oval |
19,592 | polygon methods polygon(point point point constructs polygon having the given points as vertices also accepts single parameter that is list of the vertices getpoints(returns list containing clones of the points used to construct the polygon text methods text(anchorpointstringconstructs text object that displays the given string centered at anchorpoint the text is displayed horizontally settext(stringsets the text of the object to string gettext(returns the current string getanchor(returns clone of the anchor point setface(familychanges the font face to the given family possible values are'helvetica''courier''times roman'and 'arialsetsize(pointchanges the font size to the given point size sizes from to points are legal setstyle(stylechanges font to the given style possible values are 'normal''bold''italic'and 'bold italicsettextcolor(colorsets the color of the text to color notesetfill has the same effect entry objects objects of type entry are displayed as text entry boxes that can be edited by the user of the program entry objects support the generic graphics methods move()draw(graphwin)undraw()setfill(color)and clone(the entry specific methods are given below entry(centerpointwidthconstructs an entry having the given center point and width the width is specified in number of characters of text that can be displayed getanchor(returns clone of the point where the entry box is centered gettext(returns the string of text that is currently in the entry box settext(stringsets the text in the entry box to the given string changes the font face to the given family possible values are'helvetica''courier''times roman'and 'arialsetsize(pointchanges the font size to the given point size sizes from to points are legal setstyle(stylechanges font to the given style possible values are'normal''bold''italic'and 'bold italic |
19,593 | settextcolor(colorsets the color of the text to color displaying images the graphics module also provides minimal support for displaying certain image formats into graphwin most platforms will support jpegppm and gif images display is done with an image object images support the generic methods move(dx,dy)draw(graphwin)undraw()and clone(image specific methods are given below image(centerpointfilenameconstructs an image from contents of the given filecentered at the given center point getanchor(returns clone of the point where the image is centered generating colors colors are indicated by strings most normal colors such as 'red''purple''green''cyan'etc should be available many colors come in various shadessuch as 'red ''red ','red ''red 'which are increasingly darker shades of red the graphics module also provides function for mixing your own colors numerically the function color_rgb(redgreenbluewill return string representing color that is mixture of the intensities of redgreen and blue specified these should be ints in the range - thus color_rgb( is bright redwhile color_rgb( is medium magenta summary this introduced computer graphics and object-based programming here is summary of some of the important concepts an object is computational entity that combines data and operations objects know stuff and can do stuff an object' data is stored in instance variablesand its operations are called methods every object is an instance of some class it is the class that determines what methods an object will have an instance is created by calling constructor method an object' attributes are accessed via dot notation generally computations with objects are performed by calling on an object' methods accessor methods return information about the instance variables of an object mutator methods change the value(sof instance variables the graphics module supplied with this book provides number of classes that are useful for graphics programming graphwin is an object that represents window on the screen for displaying graphics various graphical objects such as pointlinecirclerectangle |
19,594 | ovalpolygonand text may be drawn in graphwin users may interact with graphwin by clicking the mouse or typing into an entry box an important consideration in graphical programming is the choice of an appropriate coordinate system the graphics library provides way of automating certain coordinate transformations the situation where two variables refer to the same object is called aliasing it can sometimes cause unexpected results use of the clone method in the graphics library can help prevent these situations exercises review questions true/false using graphics py allows graphics to be drawn into python shell window traditionallythe upper-left corner of graphics window has coordinates ( , single point on graphics screen is called pixel function that creates new instance of class is called an accessor instance variables are used to store data inside an object the statement myshape move( , moves myshape to the point ( , aliasing occurs when two variables refer to the same object the copy method is provided to make copy of graphics object graphics window always has the title "graphics window the method in the graphics library used to get mouse click is readmouse multiple choice method that returns the value of an object' instance variable is called (namutator bfunction cconstructor daccessor method that changes the state of an object is called (nastator bmutator cconstructor dchangor what graphics class would be best for drawing squareasquare bpolygon cline drectangle |
19,595 | what command would set the coordinates of win to go from ( , in the lower-left corner to ( , in the upper-rightawin setcoords(point( , )point( , )bwin setcoords(( , )( , )cwin setcoords( dwin setcoords(point( , )point( , ) what expression would create line from ( , to ( , )aline( bline(( , )( , )cline( dline(point( , )point( , ) what command would be used to draw the graphics object shape into the graphics window winawin draw(shapebwin show(shapecshape draw(dshape draw(win which of the following computes the horizontal distance between points and aabs( - bp getx( getx(cabs( gety( gety()dabs( getx( getx() what kind of object can be used to get text input in graphics windowatext bentry cinput dkeyboard user interface organized around visual elements and user actions is called (nagui bapplication cwindower dapi what color is color_rgb( , , )ayellow bcyan cmagenta dorange discussion pick an example of an interesting real-world object and describe it as programming object by listing its data (attributeswhat it "knows"and its methods (behaviorswhat it can "do" describe in your own words the object produced by each of the following operations from the graphics module be as precise as you can be sure to mention such things as the sizepositionand appearance of the various objects you may include sketch if that helps (apoint( , (bc circle(point( , ), setfill('blue' setoutline('red' |
19,596 | (cr rectangle(point( , )point( , ) setfill(color_rgb( , , ) setwidth( (dl line(point( , )point( , ) setoutline('red ' setarrow('first'(eoval(point( , )point( , )(fshape polygon(point( , )point( , )point( , )point( , )shape setfill('orange'(gt text(point( , )"hello world!" setface("courier" setsize( setstyle("italic" describe what happens when the following interactive graphics program runsfrom graphics import def main()win graphwin(shape circle(point( , ) shape setoutline("red"shape setfill("red"shape draw(winfor in range( ) win getmouse( shape getcenter(dx getx( getx(dy gety( gety(shape move(dx,dywin close(main(programming exercises alter the program from the last discussion question in the following ways(amake it draw squares instead of circles (bhave each successive click draw an additional square on the screen (rather than moving the existing one(cprint message on the window "click again to quitafter the loopand wait for final click before closing the window |
19,597 | an archery target consists of central circle of yellow surrounded by concentric rings of redblueblack and white each ring has the same "width,which is the same as the radius of the yellow circle write program that draws such target hintobjects drawn later will appear on top of objects drawn earlier write program that draws some sort of face write program that draws winter scene with christmas tree and snowman write program that draws dice on the screen depicting straight ( or modify the graphical future value program so that the input (principal and apralso are done in graphical fashion using entry objects circle intersection write program that computes the intersection of circle with horizontal line and displays the information textually and graphically inputradius of the circle and the -intercept of the line outputdraw circle centered at ( with the given radius in window with coordinates running from - ,- to , draw horizontal line across the window with the given -intercept draw the two points of intersection in red print out the values of the points of intersection formulax + line segment information this program allows the user to draw line segment and then displays some graphical and textual information about the line segment input mouse clicks for the end points of the line segment outputdraw the midpoint of the segment in cyan draw the line print the length and the slope of the line formulasdx dy slope dy/dx length dx dy rectangle information this program displays information about rectangle drawn by the user |
19,598 | input mouse clicks for the opposite corners of rectangle outputdraw the rectangle print the perimeter and area of the rectangle formulasarea (length)(widthperimeter (length width triangle information same as previous problembut with clicks for the vertices of triangle formulasforpperimetersee length from line problem area ( )( )( cwhere aband are the lengths of the sides and + + five-click house you are to write program that allows the user to draw simple house using five mouseclicks the first two clicks will be the opposite corners of the rectangular frame of the house the third click will indicate the center of the top edge of rectangular door the door should have total width that is of the width of the house frame the sides of the door should extend from the corners of the top down to the bottom of the frame the fourth click will indicate the center of square window the window is half as wide as the door the last click will indicate the peak of the roof the edges of the roof will extend from the point at the peak to the corners of the top edge of the house frame |
19,599 | objects and graphics |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.