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 classe...
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 ex...
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 usin...
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 transfo...
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 t...
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 network...
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 co...
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 unde...
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...
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 i...
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 p...
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...
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 noti...
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...
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 point...
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 indi...
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 i...
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 ...
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 s...
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 betwe...
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 s...
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 ...
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 py...
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 book...
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...
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 ...
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 t...
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 express...
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 var...
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 under...
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 assi...
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 i...
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 c...
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 t...
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 ...
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 y...
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 printe...
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 o...
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 yea...
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...
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 spac...
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 expone...
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...
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="...
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 nu...
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 r...
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 ...
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 ...
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 ...
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 inte...
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...
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 num...
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 ...
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...
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 ...
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 importa...
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' ...
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 floatfo...
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' littl...
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...
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( i...
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 exp...
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 ...
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 nu...
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 seri...
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 fundam...
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 pr...
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 sop...
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 qu...
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 poi...
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 ...
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 orde...
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 intera...
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 ...
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 sh...
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...
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...
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...
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 ...
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 belo...
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 ...
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 ...
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 ...
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 cha...
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 in...
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 na...
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 ...
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 "but...
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 stri...
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 "gra...
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...
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 giv...
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...
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 sit...
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( , )...
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" de...
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 d...
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 a...
19,599
objects and graphics