id
int64
0
25.6k
text
stringlengths
0
4.59k
10,300
'xxx{: }yyyformat(' ''xxxayyy'xxx{: }yyy {: 'xxxayyy -substitute string -pad to spaces (left aligns by default the real fun starts when we put something inside those curly brackets these are the formatting instructions the simplest examples start with colon followed by some layout instructions (we will see what comes i...
10,301
'xxx{:< }yyyformat(' ''xxxayyy'xxx{:< }yyy {:< 'xxxayyy -align to the left (- by default strings align to the left of their space we can be explicit about this by inserting left angle bracketwhich you can think of as an arrow head pointing the direction of the alignment
10,302
'xxx{:> }yyyformat(' ''xxxayyy'xxx{:> }yyy {:> 'xxxayyy -align to the right (- if we want right aligned strings then we have to use the alignment marker
10,303
'xxx{: }yyyformat( 'xxx yyy'xxx{: }yyy {: 'xxx yyy -substitute an integer (digits -pad to spaces (right aligns by default if we change the letter to "dwe are telling the format(method to insert an integer ("digits"these align to the right by default
10,304
'xxx{:> }yyyformat( 'xxx yyy'xxx{:> }yyy 'xxx yyy {:> -align to the right (- we can be explicit about this if we want
10,305
'xxx{:> }yyyformat( 'xxx yyy'xxx{:< }yyy {:< -align to the left (-'xxx yyy and we have to be explicit to override the default
10,306
'xxx{: }yyyformat( 'xxx yyy'xxx{: }yyy {: -pad with zeroes 'xxx yyy if we precede the width number with zero then the number is padded with zeroes rather than spaces and alignment is automatic
10,307
'xxx{:+ }yyyformat( 'xxx+ yyy'xxx{:+ }yyy 'xxx+ yyy {: -always show sign if we put plus sign in front of the number then its sign is always showneven if it is positive
10,308
'xxx{:+ }yyyformat( 'xxx+ yyy'xxx{:+ }yyy {: -always show sign 'xxx+ yyy -pad with zeroes and we can combine these
10,309
'xxx{: , }yyyformat( 'xxx , yyy'xxx{: , }yyy {: , - , 'xxx , yyy adding comma between the width and the "dadds comma breaks to large numbers
10,310
'xxx{: }yyyformat( 'xxx yyy'xxx{: }yyy 'xxx yyy {: ff -substitute float - places in total - places after the point floating point numbers are slightly more complicated the width parameter has two partsseparated by decimal point the first number is the width of the entire number (just as it is for strings and integersth...
10,311
'xxx{: }yyyformat( 'xxx yyy'xxx{: }yyy {: 'xxx yyy { the default is to have six decimal points of precision and to make the field as wide as it needs to be
10,312
' {: } {: } {: }xformat('abc' 'xabcx equivalent ' { : } { : } { : }xformat('abc' 'xabcx what comes before the colonthis is selection parameter detailing what argument to insert the arguments to format(are given numbers starting at zero we can put these numbers in front of the colon
10,313
' { : } { : } { :dxformat('abc' 'xabcx ' { : } { : } { :dxformat('abc' 'xabcx we can also use them to change the order that items appear in or to have them appear more than once (or not at all
10,314
formatting '{: {: }for (wordnumberin itemsprint(formatting format(word,number)python counter py cat mat on sat the the script counter py is the same as counter py but with the new formatting for its output
10,315
contents
10,316
one beginning with python (creleased under the creative commons attribution-noncommercial-share alike united states license context you have probably used computers to do all sorts of useful and interesting things in each applicationthe computer responds in different ways to your inputfrom the keyboardmouse or file sti...
10,317
why python there are many high-level languages the language you will be learning is python python is one of the easiest languages to learn and usewhile at the same time being very powerfulit is one of the most used languages by highly productive professional programmers also python is free languageif you have your own ...
10,318
in many places there are complications that are important in the beginningbecause there is common error caused by slight misuse of the current topic if such common error is likely to make no sense and slow you downmore information is given to allow you to head off or easily react to such an error although this approach...
10,319
whether you look at the video of section or notdo look through written versioneither as first pass or to review and fill in holes from the videos be sure to stop and try things yourselfand see how they actually work on your computer look at the labeled exercises you are strongly recommended to give the unstarred ones a...
10,320
excellent holistic thinkers have hard time with this sequencingand must pay extra attention when planning code if you are like thisbe patient and be prepared to ask for help where needed what to do after you finish an exercise is importanttoo the natural thing psychologicallyparticularly if you had struggleis to think"...
10,321
note that the exampleslike this version of the tutorialare for python there were major changes to python in version making it incompatible with earlier versions if you are using python version for some good reasonyou should continue with the older version of the tutorial go to once you have the examples zip archiveyou ...
10,322
python madlib py if neither of these workget help try the program second time and make different responses sample programexplained if you want to get right to the detailed explanations of writing your own pythonyou can skip to the next section starting idle (page if you would like an overview of working programeven if ...
10,323
#/usr/bin/env python this is not technically part of the program it is there to tell the operating system what version of python to choosesince the older python is incompatible with the newer python we will mostly run programs from inside the idle programming environmentwhere this line is not needed to run just by clic...
10,324
name userpicks with new empty dictionary created by the python code dict( - addpick is the name for function defined by the sequence of instructions on lines - used to add another definition to dictionarybased on the user' input the result of these three lines is to add definitions for each of the three words animalfoo...
10,325
macopen spotlight (command-spacebarenter idle in the search field select the idle app if you have linuxthe approach depends on the installation in ubuntuyou should find idle in the programming section of the applications menu you are better starting idle from terminalwith the current directory being your python folder ...
10,326
the is the prompttelling you idle is waiting for you to type something continuing on the same line enter + be sure to end with the enter key after the shell respondsyou should see something like + the shell evaluates the line you enteredand prints the result you see python does arithmetic at the end you see further pro...
10,327
type( note the name in the last result is floatnot real or decimalcoming from the term "floating point"for reasons that will be explained laterin floatsdivisionmixed types (page enter type('hello'in your last result you see another abbreviationstr rather than string enter type([ ]strings and lists are both sequences of...
10,328
python should evaluate and print back the value of each expression of course the first one does not require any calculation it appears that the shell just echoes back what you printed the python shell is an interactive interpreter as you can seeafter you press return (or enter)it is evaluating the expression you typed ...
10,329
as you saw in the previous sectionnumbers with decimal points in them are of type float in python they are discussed more in floatsdivisionmixed types (page in early grade school you would likely say " divided by is with remainder of the problem here is that the answer is in two partsthe integer quotient and the remain...
10,330
but now look at the remainder formula- % - (- )* last sign switchboth negative - (- is so - /(- is remainder formula- (- - ( )*(- - note the sign of nonzero remainders alway matches the sign of the divisor in python side notemany other languages (javac++use different definition for integer divisionsaying its magnitude ...
10,331
string concatenation strings also have operation symbols try in the shell (noting the space after very)'very 'hotthe plus operation with strings means concatenate the strings python looks at the type of operands before deciding what operation is associated with the think of the relation of addition and multiplication o...
10,332
width once variable is assigned valuethe variable can be used in place of that value the response to the expression width is the same as if its value had been entered the interpreter does not print value after an assignment statement because the value of the expression on the right is not lost it can be recovered if yo...
10,333
there fredwithout the quotesmakes sense there are more subtleties to assignment and the idea of variable being "name fora valuebut we will worry about them laterin issues with mutable objects (page they do not come up if our variables are just numbers and strings autocompletiona handy short cut idle remembers all the v...
10,334
illegalone poor option is just leaving out the blankslike priceatopening then it may be hard to figure out where words split two practical options are underscore separatedputting underscores (which are legalin place of the blankslike price_at_opening using camel-caseomitting spaces and using all lowercaseexcept capital...
10,335
the answer looks strangeit indicates an alternate way to encode the string internally in python using escape codes escape codes are embedded inside string literals and start with backslash character they are used to embed characters that are either unprintable or have special syntactic meaning to python that you want t...
10,336
look at the editor window again you should see that different parts of the code have different colors string literals are likely green the reserved word def is likely orange look at the last two lineswhere the identifier tellstory is blackand the identifier input is likely purple only identifiers that are not predefine...
10,337
to the interpretera program source file is python module we will tend to use the more general terma program file is module note the term from the menu when running the program distinguish program code from shell textit is easy to confuse the shell and the edit windows make sure you keep them straight the hello py progr...
10,338
authors______ ''print('hello world!'#this is stupid comment after the mark most commonlythe initial documentation goes on for several linesso multi-line string delimiter is used (the triple quotesjust for completeness of illustration in this programanother form of comment is also showna comment that starts with the sym...
10,339
time input("enter the appointment time"print(interviewer"will interview"applicant"at"timethe statements are executed in the order they appear in the text of the programsequentially this is the simplest way for the execution of the program to flow you will see instructions later that alter that natural flow if we want t...
10,340
one approach would be to do that further variable names are also introduced in the example addition py file below to emphasize the distinctions in types read and run'''conversion of strings to int before addition''xstring input("enter number" int(xstringystring input("enter second number" int(ystringprint('the sum of '...
10,341
called formatthat makes substitutions into places enclosed in braces for instance the example filehello_you pycreates and prints the same string as in hello_you py from the previous section'''hello to you''illustrates format with {in print person input('enter your name'greeting 'hello{}!format(personprint(greetingthere...
10,342
'''two numeric inputsexplicit sum'' int(input("enter an integer") int(input("enter another integer")sum + sentence 'the sum of {and {is {format(xysumprint(sentenceconversion to strings was not needed in interview py (everything started out as string in addition pyhoweverthe automatic conversion of the integers to strin...
10,343
try the program with other data now that you have few building blocksyou will see more exercises where you need to start to do creative things you are encouraged to go back and reread learning to problem-solve (page addition format exercise write version of exercise for addition (page )add pythat uses the string format...
10,344
print("happy birthday to you!"print("happy birthday to you!"print("happy birthdaydear emily "print("happy birthday to you!"you would probably not repeat the whole song to let others know what to sing you would give request to sing via descriptive name like "happy birthday to emilyin python we can also give name like ha...
10,345
in many cases we will use feature of program execution in idlethat after program execution is completedthe idle shell still remembers functions defined in the program this is not true if you run program by selecting it directly in the operating system look at the example program birthday py see it just adds two more li...
10,346
print("happy birthday to you!"print("happy birthdaydear andre "print("happy birthday to you!"happybirthdayemily(happybirthdayandre(againeverything is definitions except the last two lines they are the only lines executed directly the calls to the functions happen to be in the same order as their definitionsbut that is ...
10,347
return to the end of line back from happybirthdayandre function calldone with main return to the end of line back from mainat the end of the program there is one practical difference from the previous version after executionif we want to give another round of happy birthday to both personswe only need to enter one furt...
10,348
print("happy birthdaydear person "print("happy birthday to you!" happybirthday('emily'happybirthday('andre'in the definition heading for happybirthdayperson is referred to as formal parameter this variable name is placeholder for the real name of the person being sung to the last two lines of the programagainare the on...
10,349
using function whose parameters refer to the parts that are different in different situations then the code is written to be simultaneously appropriate for the separate specific situationswith the substitutions of the right parameter values you can go back to having main function againand everything works run birthday ...
10,350
now that we have nested function callsit is worth looking further at tracebacks from execution errors if add line to main in birthday pyhappybirthday( as in example file birthdaybad pyand then run ityou get something close totraceback (most recent call last)file "/hands-on/examples/birthdaybad py"line in main(file "/ha...
10,351
the actual parameters in the function call are evaluated left to rightand then these values are associated with the formal parameter names in the function definitionalso left to right for example function call with actual parametersf(actual actual actual )calling function with definition headingdef (formal formal forma...
10,352
it is as if the statement temporarily became print( and similarly when executing print( ( ( )the interpreter first evaluates ( and effectively replaces the call by the returned result as if the statement temporarily became print( ( )and then the interpreter evaluates ( and effectively replaces the call by the returned ...
10,353
compare return py and addition pyfrom the previous section both use functions both printbut where the printing is done differs the function sumproblem prints directly inside the function and returns nothing explicitly on the other hand lastfirst does not print anything but returns string the caller gets to decide what ...
10,354
writers of functions and consumers of the other functions called inside their functions it is useful to keep those two roles separatethe user of an already written function needs to know the name of the function the order and meaning of parameters what is returned or produced by the function how this is accomplished is...
10,355
with parameter passingthe parameter name in the function does not need to match the name of the actual parameter in main the definition of could just as well have beendef (whatever)print(whateverglobal constants if you define global variables (variables defined outside of any function definition)they are visible inside...
10,356
spanish dict(spanish['hello''holaspanish['yes''sispanish['one''unospanish['two''dosspanish['three''tresspanish['red''rojospanish['black''negrospanish['green''verdespanish['blue''azulprint(spanish['two']print(spanish['red']first an empty dictionary is created using dict()and it is assigned the descriptive name spanish t...
10,357
main(this code illustrates several things about functions firstlike whole filesfunctions can have documentation string immediately after the definition heading it is good idea to document the return valuethe dictionary that is created is returnedbut the local variable name in the functionspanishis lost when the functio...
10,358
note the form of the string assigned the name numberformatit has the english words for numbers in braces where we want the spanish definitions substituted (this is unlike in string format operation (page )where we had empty braces or numerical index inside as in string format operation (page )the second line uses metho...
10,359
look at madlib py againsee how we have used most of the ideas so far if you want more descriptionyou might look at section sample programexplained (page again (or for the first time)it should make much more sense now we will use madlib py as basis for more substantial modifications in structure in the revised mad lib p...
10,360
'''fancier -string example for formatting'' sum prod print( '{ { {sum}{ { {prod'see the directly before the literal format string automatically substituting local variable values quotient string dictionary exercise create quotientdict py by modifying quotientreturn py in quotient string return exercise (page so that th...
10,361
line is executeda value is given to xbut is still undefined then gets value in line the comment on the right summarizes what is happening since has the value when line startsx+ is the same as + in line three we use the fact that the right side of an assignment statement uses the values of variables when the line starts...
10,362
basic for loops try the following in the shell you get sequence of continuation lines before the shell responds after seeing the colon at the end of the first linethe shell knows later lines are to be indented be sure to enter another empty line (just press enter at the end to get the shell to respond for count in [ ]p...
10,363
for count in [ ]print(countprint('yescountprint('done counting 'for color in ['red''blue''green']print(colorin filewhere the interpreter does not need to respond immediatelythe blank line is not necessary insteadas with function definition or any other format with an indented blockyou indicate being past the indented b...
10,364
if you wish to see or run the whole program with this small modificationsee the example madlibloop py common naming convention is used in the programeach element in the list is cuewhile the list with all the elements is named with the plural cues in later situations make list name be the plural of the variable name use...
10,365
def tripleall(nums)''print triple each of the numbers in the list nums tripleall([ ] tripleall([- ]- ''simple repeat loop the examples above all used the value of the variable in the for loop heading an even simpler for loop usage is when you just want to repeat the exact same thing specific number of times in that cas...
10,366
print(itemand just go through the list and do it for each one (copy and run if you like items ['red''orange''yellow''green'for item in itemsprint(itemclearly the more elaborate version with numbers has pattern with some consistencyeach line is at least in the formnumber item but the number changes each timeand the numb...
10,367
line item 'red'red'red'orange'orange'orange'yellow'yellow'yellow'green'green'green'greennumber comment set items to ['red''orange','yellow''green'start with item as first in sequence print red + on to the next element in sequence print orange = + on to the next element in sequence print yellow = + on to the last elemen...
10,368
functions are handy for encapsulating an idea for use and reuse in programand also for testing we can write function to number listand easily test it with different data read and run the example program numberentries py''use function to number the entries in any list''def numberlist(items)'''print each item in list ite...
10,369
since the list may be arbitrarily longyou need loop hence you must find pattern so that you can keep reusing the same statements in the loop obviously you are using each number in the sequence in order you also generate sum in each stepwhich you reuse in the next step the pattern is differenthoweverin the first line + ...
10,370
initialize the accumulation to include none of the sequence (sum herefor item in sequence new value of accumulation result of combining item with last value of accumulation this pattern will work in many other situations besides adding numbers english loop terminologyof course you need to be able to go from an english ...
10,371
[ line sum num comment set nums to [ ]skip line doc string test sumlist exercise write program testsumlist py which includes main function to test the sumlist function several times include test for the extreme casewith an empty list join all exercise complete the following function this starting code is in joinallstub...
10,372
you can run this code and see that it produces the wrong answer if you play computer on the call to numberlist(['apples''pears''bananas'])you can see the problemline item 'apples'apples'apples'apples'pears'pears'pearsnumber comment set items to ['apples''pears''bananas'start with item as first in sequence print apples ...
10,373
play computer odd loop exercise work in word processor (not idle!)starting from example playcomputerstub rtfand save the file as playcomputer rtf the file has tables set up for this and the following two exercise play computer on the following code exercise play computer loop for in [ ] * print(xreality check is printe...
10,374
reality check is printed the table headings and the first row of the table for this exercise are shown below line - comment remember definition you will revisit line several timeswith table lines for function execution interspersed look at the example above which has table showing function returning value twicethe prin...
10,375
floatsdivisionmixed types as you moved on in school from your first integer division to fractions and decimalsyou probably thought of / as fraction and could convert to decimal python can do decimal calculationstooapproximately try all set-off lines in this section in the shell / / there is more going on here than meet...
10,376
** * ** if you expected for the second expressionremember exponentiation has even higher precedence than multiplication and division ** is * * or and * is exponents do not need to be integers useful example is the powerit produces square root try in the shell * * the result of power operation is of int type only if bot...
10,377
the instructions for the data to insert can also be given by position index (from the optional end of string format operation (page )) 'longer{ }shorter{ fformat( 'longer shorter in each of these approachesthe colon and formatting specification come at the end of the expression inside the bracesjust before the closing ...
10,378
typeface typewriter font emphasized bold normal text meaning text to be written verbatim place where you can use an arbitrary expression place where you can use an arbitrary identifier description of what goes in that positionwithout giving explicit syntax if there are several variations on particular part of the synta...
10,379
(clogical errorswhen python detects nothing illegalbut you do not get the results you desire these errors are the hardest to trace down playing computer and additional print functions help [more playing computer (page ) type int(short for integer)(aliteral integer values may not contain decimal point [floatsdivisionmix...
10,380
integersubstitute numerical value rounded to the specified number of places beyond the decimal point [floatsdivisionmixed types (page )example'word{}int{}formatted float{ fformat('joe' evaluates to'wordjoeint formatted float ii stringformatexpression format*dictionary the format expressions are the same as above except...
10,381
evaluates to the value in the dictionary dictname coming from the key obtained by evaluating keyexpression [definition and use of dictionaries (page ) type of nonethis literal value has its own special type none indicates the absence of regular object identifiers (aidentifiers are names for python objects [literals and...
10,382
(beven if there are no parametersthe parentheses must be included to distinguish the name of the function from request to call the function [ first function definition (page )(ceach expression is called an actual parameter each actual parameter is evaluated and the values are passed to the code for the functionwhich ex...
10,383
(hformatexpression formatstring if expression is numericthe format string can be in the form # 'where the gets replaced by nonnegative integerand the result is string with the value of the expression rounded to the specified number of digits beyond the decimal point [floatsdivisionmixed types (page ) functions defined ...
10,384
(bas the very first entry in the body of functionthis should describe[definition and use of dictionaries (page ) the return value of the function (if there is oneii anything about the parameters that is not totally obvious from the names iii anything about the results from the function that is not obvious from the name...
10,385
new value of accumulation partial result where the partial result comes from combining item with the current value of accumulation playing computerfollowing code line by line of execution this either tests that you understand your code (and it works rightor it helps you find where it goes wrong [updating variables (pag...
10,386
two objects and methods stringspart iii object orientation python is an object-oriented language every piece of data and even functions and types are objects the term objectoriented is used to distinguish python from earlier languagesclassified as procedural languageswhere types of data and the operations on them were ...
10,387
test yourself in the shellhow would you use this string and both the lower and upper methods to create the string 'hello!hello!'hint answer many methods also take additional parameters between the parenthesesusing the more general syntaxobject method(parametersthe first of many such methods we will introduce is countsy...
10,388
object method(parametershas been illustrated so far with just the object type strbut it applies to all types later in the tutorial methods such as the following will be discussedif seq is listseq append(elementappends element to the end of the list if mydata is filemydata read(will read and return the entire contents o...
10,389
be careful remember what the initial index isstring slices it is also useful to extract larger pieces of string than single character that brings us to slices try this expression using slice notationcontinuing in the shells[ : note that [ is the first character past the slice the simplest syntax for slice of string iss...
10,390
through the whole string if an integer value is given for startthe search starts at index start if an integer value is given for endthe search ends before index end in other words if start and end appearthen the search is through the slice [start end]but the index returned is still counted from the beginning of for exa...
10,391
index variables all the concrete examples in the last two sections used literal numbers for the indices that is fine for learning the ideabut in practicevariables or expressions are almost always used for indices as usual the variable or expression is evaluated before being used try in idle and see that the example pro...
10,392
return new string obtained by joining together the sequence of strings into one stringinterleaving the string sep between sequence elements for example (continuing in the shell from the previous sectionusing seq)followjoin(seq'gotear some strings apart!'join(seq'go:tearsomestringsapart!'//join(seq'go://tear//some//stri...
10,393
further exploration as the dir(''list showedthere are many more operations on strings than we have discussedand there are further variations of the ones above with more parameters methods startswithendswithand replace are discussed later in more string methods (page if you want to reach systematic reference from inside...
10,394
in earlier versions of the accumulation loopwe needed an assignment statement to change the object doing the accumulatingbut now the method append modifies its list automaticallyso we do not need an assignment statement read and try the example program multiply pydef multiplyall(numlistmultiplier)# '''return new list c...
10,395
bb zz predict the result of the followingand then paste it into the shell and test (you may not guess python' orderbut see if you can get the right length and the right elements in some order set(['animal''food''animal''food''food''city']constructors we have now seen several examples of the name of type being used as f...
10,396
repeat the correct number of times this will work in this case (there is more efficient approach after we introduce while statements (page )suggested in mad lib while exercise (page firsthow many times do we want to pull out key once for each embedded format so how do we count thosethe count method is obviously way to ...
10,397
formatstring find('{'but that is not the full solution if we look at our concrete examplethe value returned is not how in general would we locate the beginning of the slice we wantwe do not want the position of the '{'but the position just after the '{since the length of '{is the correct position is + we can generalize...
10,398
return keylist look the code over and see that it makes sense see how we continuously modify startendkeyand keylist since we have coded this new part as functionit is easy to test without running whole revised mad lib program we can just run this function on some test datalike the original storyand see what it does run...
10,399
ideas that the names correspond to when using sequences like lists or stringsyou generally need names not only for the whole collectionbut also parts like items and characters or substringsand often indices that locate parts of the collection plan the overall approach to the problem using mixture of python and suggesti...