id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
19,600 | sequencesstringslistsand files objectives to understand the string data type and how strings are represented in the computer to be familiar with various operations that can be performed on strings through built-in functions and string methods to understand the basic idea of sequences and indexing as they apply to pytho... |
19,601 | there is no differencejust be sure to use matching set strings can also be saved in variablesjust like any other data here are some examples illustrating the two forms of string literalsstr "hellostr 'spamprint(str str hello spam type(str type(str you already know how to print strings you have also seen how to get stri... |
19,602 | greet "hello bobgreet[ 'hprint(greet[ ]greet[ ]greet[ ] print(greet[ - ] notice thatin string of charactersthe last character is at position because the indexes start at this is probably also good time to remind you about the difference between string objects and the actual printed output in the interactions above the ... |
19,603 | operator len(for in meaning concatenation repetition indexing slicing length iteration through characters table python string operations indexing and slicing are useful operations for chopping strings into smaller pieces the string data type also supports operations for putting strings together two handy operators are ... |
19,604 | many computer systems use username and password combination to authenticate system users the system administrator must assign unique username to each user oftenusernames are derived from the user' actual name one scheme for generating usernames is to use the user' first initial followed by up to seven letters of the us... |
19,605 | gram is an int that represents month number ( - )and the output is the abbreviation for the corresponding month for exampleif the input is then the output should be marfor march at firstit might seem that this program is beyond your current ability experienced programmers recognize that this is decision problem that is... |
19,606 | monthabbrev months[pos:pos+ print the result print("the month abbreviation is"monthabbrev "main(notice the last line of this program uses string concatenation to put period at the end of the month abbreviation here is sample of program outputenter month number ( - ) the month abbreviation is apr one weakness of the "st... |
19,607 | in later we'll put all sorts of things into lists like pointsrectanglesdicebuttonsand even studentsusing list of stringswe can rewrite our month abbreviation program from the previous section and make it even simpler month py program to print the month abbreviationgiven its number def main()months is list used as looku... |
19,608 | mylist[ mylist[ mylist [ mystring "hello worldmystring[ 'lmystring[ 'ztraceback (most recent call last)file ""line in typeerror'strobject does not support item assignment the first line creates list of four numbers indexing position returns the value (as usualindexes start at the next command assigns the value to the i... |
19,609 | sequencesstringslistsand files about the encoding/decoding process in the early days of computingdifferent designers and manufacturers used different encodings you can imagine what headache this was for people transferring data between different systems consider situation that would result ifsaypcs and macintosh comput... |
19,610 | different values that' more than enough to represent every possible ascii character (in factascii is only bit codebut single byte is nowhere near sufficient for storing all the , possible unicode characters to get around this problemthe unicode standard defines various encoding schemes for packing unicode characters in... |
19,611 | print("\nhere are the unicode codes:"loop through the message and print out the unicode values for ch in messageprint(ord(ch)end="print(blank line before prompt main(we can use the program to encode important messages this program converts textual message into sequence of numbers representing the unicode encoding of th... |
19,612 | before the loopthe accumulator variable message is initialized to be an empty stringthat is string that contains no characters (""each time through the loop number from the input is converted into an appropriate character and appended to the end of the message constructed so far the algorithm seems simple enoughbut eve... |
19,613 | " split([' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' 'notice that the resulting list is not list of numbersit is list of strings it just so happens these strings contain only digits and could be interpreted as numbers all that we need now is way of converting string containing digits into python number of coursewe a... |
19,614 | message message chr(codenumconcatentate character to message print("\nthe decoded message is:"messagemain(study this program bitand you should be able to understand exactly how it accomplishes its task the heart of the program is the loop for numstr in instring split()codenum eval(numstrmessage message chr(codenumthe s... |
19,615 | lower('helloi came here for an arguments upper('helloi came here for an arguments replace(" ""you"'helloyou came here for an arguments center( 'helloi came here for an arguments center( helloi came here for an argument count(' ' find(',' join(["number""one,""the""larch"]'number onethe larch"spamjoin(["number""one,""the... |
19,616 | lists have methods too in the last section we took look at some of the methods for manipulating string objects like stringslists are also objects and come with their own set of "extraoperations since this is primarily concerned with text-processingwe'll save the detailed discussion of various list methods for for later... |
19,617 | get the message to encode instring input("please enter the unicode-encoded message"loop through each substring and build unicode message chars [for numstr in instring split()codenum eval(numstrconvert digits to number chars append(chr(codenum)accumulate new character message "join(charsprint("\nthe decoded message is:"... |
19,618 | encoding program then sophisticated mathematical algorithms are employed to transform these numbers into other numbers usuallythe transformation is based on combining the message with some other special value called the key in order to decrypt the messagethe party on the receiving end needs to have an appropriate key s... |
19,619 | sequencesstringslistsand files datestr input("enter date (mm/dd/yyyy)"monthstrdaystryearstr datestr split("/"here have gotten the date as string and split it at the slashes then "unpackedthe list of three strings into the variables monthstrdaystrand yearstr using simultaneous assignment the next step is to convert mont... |
19,620 | in general thenif you're converting something that supposed to be an intit' safest to use int rather than eval returning to the date conversion algorithmwe can turn monthstr into number using int and then use this value to look up the correct month name here is the codemonths ["january""february""march""april""may""jun... |
19,621 | str( ' value str(value' print("the value is"str(value"the value is notice particularly the last example by turning value into stringwe can use string concatenation to put period at the end of sentence if we didn' first turn value into stringpython would interpret the as numerical operation and produce an errorbecause i... |
19,622 | print("the date is"date "or"date +"main(notice how string concatenation is used to produce the required output here is how the result looksplease enter daymonthand year numbers the date is or may string formatting as you have seenbasic string operations can be used to build nicely formatted output this technique is use... |
19,623 | sequencesstringslistsand files curly braces ({}inside the template-string mark "slotsinto which the provided values are inserted the information inside the curly braces tells which value goes in the slot and how the value should be formatted the python formatting operator is very flexiblewe'll cover just some basics he... |
19,624 | 'this float has width and precision "compare { and { : }format( 'compare and notice that for normal (not fixed-pointfloating point numbersthe precision specifies the number of significant digits to print for fixed-point (indicated by the at the end of the specifierthe precision gives the number of decimal places in the... |
19,625 | change py program to calculate the value of some change in dollars this version represents the total cash in cents def main()print("change counter\ "print("please enter the count of each coin type "quarters eval(input("quarters")dimes eval(input("dimes")nickels eval(input("nickels")pennies eval(input("pennies")total qu... |
19,626 | multi-line strings conceptuallya file is sequence of data that is stored in secondary memory (usually on disk drivefiles can contain any data typebut the easiest files to work with are those that contain text files of text have the advantage that they can be read and understood by humansand they are easily created and ... |
19,627 | sequencesstringslistsand files file processing the exact details of file-processing differ substantially among programming languagesbut virtually all languages share certain underlying file manipulation concepts firstwe need some way to associate file on disk with an object in program this process is called opening fil... |
19,628 | read(returns the entire remaining contents of the file as single (potentially largemulti-linestring readline(returns the next line of the file that is all text up to and including the next newline character readlines(returns list of the remaining lines in the file each list item is single line including the newline cha... |
19,629 | sequencesstringslistsand files one way to loop through the entire contents of file is to read in all of the file using readlines and then loop through the resulting list infile open(somefile" "for line in infile readlines()process the line here infile close(of coursea potential drawback of this approach is the fact tha... |
19,630 | userfile py program to create file of usernames in batch mode def main()print("this program creates file of usernames from "print("file of names "get the file names infilename input("what file are the names in"outfilename input("what file should the usernames go in"open the files infile open(infilename" "outfile open(o... |
19,631 | strings are sequences of characters string literals can be delimited with either single or double quotes strings and lists can be manipulated with the built-in sequence operations for concatenation (+)repetition (*)indexing ([])slicing ([:])and length (len() for loop can be used to iterate through the characters of str... |
19,632 | string always contains single line of text in python " " is " python lists are mutablebut strings are not ascii is standard for representing characters using numeric codes the split method breaks string into list of substringsand join does the opposite substitution cipher is good way to keep sensitive information secur... |
19,633 | discussion given the initial statementss "spams "ni!show the result of evaluating each of the following string expressions ( "the knights who says ( (cs [ (ds [ : (es [ [: (fs [- (gs upper((hs upper(ljust( given the same initial statements as in the previous problemshow python expression that could construct each of th... |
19,634 | (emsg "for ch in "secret"msg msg chr(ord(ch)+ print(msg show the string that would result from each of the following string formatting operations if the operation is not legalexplain why ( "looks like { and { for breakfastformat("eggs""spam"( "there is { { { { }format( ,"spam" "you"( "hello { }format("susan""computewel... |
19,635 | expand your solution to the previous problem to allow the calculation of complete name such as "john marvin zelleor "john jacob jingleheimer smith the total value is just the sum of the numeric values of all the names caesar cipher is simple substitution cipher based on the idea of shifting each letter of the plaintext... |
19,636 | write an improved version of the future value program from your program will prompt the user for the amount of the investmentthe annualized interest rateand the number of years of the investment the program will then output nicely formatted table that tracks the value of the investment year by year your output might lo... |
19,637 | |
19,638 | defining functions objectives to understand why programmers divide programs up into sets of cooperating functions to be able to define new functions in python to understand the details of function calls and parameter passing in python to write programs that use functions to reduce code duplication and increase program ... |
19,639 | 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(p... |
19,640 | and easier to maintain before fixing up the future value programlet' take look at what functions have to offer functionsinformally you can think of function as subprogram-- small program inside of program the basic idea of function is that we write sequence of statements and give that sequence name the instructions can... |
19,641 | defining functions we have defined new function called happy here is an example of what it doeshappy(happy birthday to youinvoking the happy command causes python to print line of the song now we can redo the verse for fred using happy let' call our new version singfred def singfred()happy(happy(print("happy birthdayde... |
19,642 | happy birthdaydear fred happy birthday to youhappy birthday to youhappy birthday to youhappy birthdaydear lucy happy birthday to youwell nowthat certainly seems to workand we've removed some of the duplication by defining the happy function howeversomething still doesn' feel quite right we have two functionssingfred an... |
19,643 | sing("lucy"print(sing("elmer"it doesn' get much easier than that here is the complete program as module file happy py def happy()print("happy birthday to you!"def sing(person)happy(happy(print("happy birthdaydear"person "happy(def main()sing("fred"print(sing("lucy"print(sing("elmer"main( future value with function now ... |
19,644 | bar setwidth( bar draw(winlet' try to combine these two into single function that draws bar on the screen in order to draw the barwe need some information specificallywe need to know what year the bar will be forhow tall the bar will beand what window the bar will be drawn in these three values will be supplied as para... |
19,645 | text(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- ) 'draw(wintext(point(- )' 'draw(windrawbar(win principalfor year in range( )principal principal ( aprdrawbar(winyearprincipalinput("press to quit "win close(main(you can see how drawbar has eliminated the duplicated code should we wish to change the appearan... |
19,646 | the name of the function must be an identifierand formal-parameters is (possibly emptylist of variable names (also identifiersthe formal parameterslike all variables used in the functionare only accessible in the body of the function variables with identical names elsewhere in the program are distinct from the formal p... |
19,647 | def happy()def sing(person)def main()print("happy birthday to you!"happy(sing("fred"person "fredhappy(print(print("happy birthdaydear"person "sing("lucy"happy(person"fredfigure snapshot of completed call to happy function the body of happy consists of single print this statement is executedand then control returns to w... |
19,648 | statements in main have caused sing to execute twice and happy to execute six times overallnine total lines of output were generated def main()sing("fred"print(sing("lucy"def sing(person)happy(happy(print("happy birthdaydear"person "happy(figure completion of second call to sing hopefully you're getting the hang of how... |
19,649 | defining functions functions that return values one way to get information from function is by having it return value to the caller you have already seen numerous examples of this type of function for exampleconsider this call to the sqrt function from the math librarydiscrt math sqrt( * * *chere the value of * * * is ... |
19,650 | programtriangle py import math from graphics import def square( )return def distance( )dist math sqrt(square( getx( getx()square( gety( gety())return dist 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... |
19,651 | defining functions you can see how distance is called three times in one line to compute the perimeter of the triangle using function here saves quite bit of tedious coding sometimes function needs to return more than one value this can be done by simply listing more than one expression in the return statement as silly... |
19,652 | functions that modify parameters return values are the main way to send information from function back to the part of the program that called the function in some casesfunctions can also communicate back to the calling program by making changes to the function parameters understanding when and how this is possible requ... |
19,653 | oun def addinterest(balancerate)def test()=am nce newbalance balance ( ratea amount ba = balance newbalance rate rat addinterest(amount,rateprint(amountbalance amount rate rate figure transfer of control to addinterest executing the first line of addinterest creates new variable newbalance now comes the key step the ne... |
19,654 | parameters by value some programming languages ( +and ada)do allow variables themselves to be sent as parameters to function such mechanism is called passing parameters by reference when variable is passed by referenceassigning new value to the formal parameter actually changes the value of the parameter variable in th... |
19,655 | addinterest py def addinterest(balancesrate)for in range(len(balances))balances[ibalances[ ( +ratedef test()amounts [ rate addinterest(amountsrateprint(amountstest(take moment to study this program the test function starts by setting amounts to be list of four values then the addinterest function is called sending amou... |
19,656 | value of the variable amounts is now list object that itself contains four int values it is this list object that gets passed to addinterest and is therefore also the value of balances next addinterest executes the loop goes through each index in the range length and updates that item in balances the result is shown in... |
19,657 | modular as the algorithms that you design get more complexit gets more and more difficult to make sense out of programs humans are pretty good at keeping track of eight to ten things at time when presented with an algorithm that is hundreds of lines longeven the best programmers will throw up their hands in bewildermen... |
19,658 | but--not to put too fine point on it--this function is just too long one way to make the program more readable is to move some of the details into separate function for examplethere are eight lines in the middle that simply create the window where the chart will be drawn we could put these steps into value returning fu... |
19,659 | def createlabeledwindow()window graphwin("investment growth chart" window setbackground("white"window setcoords(- ,- text(point(- ) 'draw(windowtext(point(- ) 'draw(windowtext(point(- ) 'draw(windowtext(point(- ) 'draw(windowtext(point(- )' 'draw(windowreturn window def drawbar(windowyearheight)bar rectangle(point(year... |
19,660 | multiple times from many different places in program parameters allow functions to have changeable parts the parameters appearing in the function definition are called formal parametersand the expressions appearing in function call are known as actual parameters call to function initiates four step process the calling ... |
19,661 | multiple choice the part of program that uses function is called the auser bcaller ccallee dstatement python function definition begins with adef bdefine cfunction ddefun function can send output back to the program with (nareturn bprint cassignment dsase formal and actual parameters are matched up by aname bposition c... |
19,662 | parameters are an important concept in defining functions (awhat is the purpose of parameters(bwhat is the difference between formal parameter and an actual parameter(cin what ways are parameters similar to and different from ordinary variables functions can be thought of as miniature (sub)programs inside of other prog... |
19,663 | the ants go marching one by onehurrahhurrahthe ants go marching one by onehurrahhurrahthe ants go marching one by onethe little one stops to suck his thumband they all go marching down in the ground to get out of the rain boomboomboomthe ants go marching two by twohurrahhurrahthe ants go marching two by twohurrahhurrah... |
19,664 | do programming exercise from using function grade(scorethat returns the letter grade for score do programming exercise from using function acronym(phrasethat returns an acronym for phrase supplied as string write and test function to meet this specification squareeach(numsnums is list of numbers modifies the list by sq... |
19,665 | defining functions |
19,666 | decision structures objectives to understand the programming pattern simple decision and its implementation using python if statement to understand the programming pattern two-way decision and its implementation using python if-else statement to understand the programming pattern multi-way decision and its implementati... |
19,667 | decision structures exampletemperature warnings let' start by getting the computer to make simple decision for an easy examplewe'll return to the celsius to fahrenheit temperature conversion program from rememberthis was written by susan computewell to help her figure out how to dress each morning in europe here is the... |
19,668 | input celsius temperature farenheit / celsius print fahrenheit fahrenheit no fahrenheit no yes print heat warning yes print cold warning figure flowchart of temperature conversion program with warnings here is how the new design translates into python codeconvert py program to convert celsius temps to fahrenheit this v... |
19,669 | the body is just sequence of one or more statements indented under the if heading in convert py there are two if statementsboth of which have single statement in the body the semantics of the if should be clear from the example above firstthe condition in the heading is evaluated if the condition is truethe sequence of... |
19,670 | python <=>!mathematics <> meaning less than less than or equal to equal to greater than or equal to greater than not equal to notice especially the use of =for equality since python uses the sign to indicate an assignment statementa different symbol is required for the concept of equality common mistake in python progr... |
19,671 | decision structures so farmost of our programs have had line at the bottom to invoke the main function main(as you knowthis is what actually starts program running these programs are suitable for running directly in windowing environmentyou might run file by (double-)clicking its icon or you might type command like pyt... |
19,672 | two-way decisions now that we have way to selectively execute certain statements in program using decisionsit' time to go back and spruce up the quadratic equation solver from here is the program as we left itquadratic py program that computes the real roots of quadratic equation notethis program crashes if the equatio... |
19,673 | quadratic py import math def main()print("this program finds the real solutions to quadratic\ "abc eval(input("please enter the coefficients (abc)")discrim if discrim > discroot math sqrt(discrimroot (- discroot( aroot (- discroot( aprint("\nthe solutions are:"root root main(this version first computes the value of the... |
19,674 | no discrim calculate roots yes print "no rootsfigure quadratic solver as two-way decision should either print that there are no real roots or it should calculate and display the roots this is an example of two-way decision figure illustrates the situation in pythona two-way decision can be implemented by attaching an e... |
19,675 | discroot math sqrt( croot (- discroot( aroot (- discroot( aprint("\nthe solutions are:"root root main(this program fills the bill nicely here is sample session that runs the new program twicequadratic main(this program finds the real solutions to quadratic please enter the coefficients (abc) , , the equation has no rea... |
19,676 | when handle the case of double root when handle the case of two distinct roots one way to code this algorithm is to use two if-else statements the body of an if or else clause can contain any legal python statementsincluding other if or if-else statements putting one compound statement inside of another is called nesti... |
19,677 | reflect the true three-fold decision of the original problem imagine if we needed to make fiveway decision using this technique the if-else structures would nest four levels deepand the python code would march off the right-hand edge of the page there is another way to write multi-way decisions in python that preserves... |
19,678 | print("\nthe solutions are:"root root main( exception handling our quadratic program uses decision structures to avoid taking the square root of negative number and generating an error at run-time this is common pattern in many programsusing decisions to protect against rare but possible errors in the case of the quadr... |
19,679 | decision structures abc input("please enter the coefficients (abc)"discroot math sqrt( croot (- discroot( aroot (- discroot( aprint "\nthe solutions are:"root root except valueerrorprint "\nno real rootsmain(notice that this is basically the very first version of the quadratic program with the addition of try except ar... |
19,680 | bad set of coefficients if the user fails to type the correct number of inputsthe program generates different kind of valueerror if the user accidentally types an identifier instead of numberthe program generates nameerror if the input is not valid python expressionit generates syntaxerror if the user types in valid py... |
19,681 | assign that variable the actual exception object in this casei turned the exception into string and looked at the message to see what caused the valueerror notice that this text is exactly what python prints out if the error is not caught ( "valueerrormath domain error"if the exception doesn' match any of the expected ... |
19,682 | it would seem we just need to preface each one with the appropriate condition( )so that it is executed only in the proper situation let' consider the first possibilitythat is the largest to determine that is actually the largestwe just need to check that it is at least as large as the other two here is first attemptif ... |
19,683 | decision structures summing up this approachour algorithm is basically checking each possible value against all the others to determine if it is the largest with just three values the result is quite simplebut how would this solution look if we were trying to find the max of five valuesthen we would need three boolean ... |
19,684 | yes no > yes max > no max yes max = no max figure flowchart of the decision tree approach to max of three yourself how you would solve the problem if you were asked to do the job for finding the max of three numbersyou probably don' have very good intuition about the steps you go through you' just look at the numbers a... |
19,685 | max max max max max figure flowchart of sequential approach to the max of three problem if maxmax if maxmax if maxmax it should not be surprising that the last solution scales to larger problemswe invented the algorithm by explicitly considering how to solve more complex problem in factyou can see that the code is very... |
19,686 | set max to be the first value max eval(input("enter number >")now compare the - successive values for in range( - ) eval(input("enter number >")if maxmax print("the largest value is"maxmain(this code uses decision nested inside of loop to get the job done on each iteration of the loopmax contains the largest value seen... |
19,687 | decision structures be the computer especially for beginning programmersone of the best ways to formulate an algorithm is to simply ask yourself how you would solve the problem there are other techniques for designing good algorithms (see )howeverthe straightforward approach is often simpleclearand efficient enough gen... |
19,688 | exercises review questions true/false simple decision can be implemented with an if statement in python conditions is written as / strings are compared by lexicographic ordering two-way decision is implemented using an if-elif statement the math sqrt function cannot compute the square root of negative number single try... |
19,689 | in pythonthe body of decision is indicated by aindentation bparentheses ccurly braces da colon structure in which one decision leads to another set of decisionswhich leads to another set of decisionsetc is called decision anetwork bweb ctree dtrap taking the square root of negative value with math sqrt produces (navalu... |
19,690 | print "larchprint "doneshow the output that would result from each of the following possible inputs( ( ( ( ( ( how is exception-handling using try/except similar to and different from handling exceptional cases using ordinary decision structures (variations on if)programming exercises many companies pay time-and- -half... |
19,691 | babysitter charges $ an hour until : pm when the rate drops to $ an hour (the children are in bedwrite program that accepts starting time and ending time in hours and minutes and calculates the total babysitting bill you may assume that the starting and ending times are in single hour period partial hours should be app... |
19,692 | worth fewer points down to for white the program should output score for each click and keep track of running sum for the entire series write program to animate circle bouncing around window the basic idea is to start the circle somewhere in the interior of the window use variables dx and dy (both initialized to to con... |
19,693 | decision structures |
19,694 | loop structures and booleans objectives to understand the concepts of definite and indefinite loops as they are realized in the python for and while statements to understand the programming patterns interactive loop and sentinel loop and their implementations using python while statement to understand the programming p... |
19,695 | loop structures and booleans suppose we want to write program that can compute the average of series of numbers entered by the user to make the program generalit should work for any size set of numbers you know that an average is calculated by summing up the numbers and dividing by the count of how many numbers there a... |
19,696 | wellthat wasn' too bad knowing couple of common patternscounted loop and accumulatorgot us to working program with minimal difficulty in design and implementation hopefullyyou can see the worth of committing these sorts of programming cliches to memory indefinite loops our averaging program is certainly functionalbut i... |
19,697 | no yes figure flowchart of while loop notice that the while version requires us to take care of initializing before the loop and incrementing at the bottom of the loop body in the for loopthe loop variable is handled automatically the simplicity of the while statement makes it both powerful and dangerous because it is ... |
19,698 | on pcif all else failsthere is always the trusty reset button on your computer the best idea is to avoid writing infinite loops in the first place common loop patterns interactive loops one good use of the indefinite loop is to write interactive loops the idea behind an interactive loop is that it allows the user to re... |
19,699 | moredata "yeswhile moredata[ =" " eval(input("enter number >")sum sum count count moredata input("do you have more numbers (yes or no)"print("\nthe average of the numbers is"sum countmain(notice this program uses string indexing (moredata[ ]to look just at the first letter of the user' input this allows for varied resp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.