id int64 0 25.6k | text stringlengths 0 4.59k |
|---|---|
800 | is formally described as follows (brackets denote optional components and are not coded literally)[[fill]align][sign][#][ ][width][,]precision][typecodein thisfill can be any fill character other than or }align may be =or ^for left alignmentright alignmentpadding after sign characteror centered alignmentrespectivelysig... |
801 | method over the formatting expression (see the related note ahead)'{: {: }format('spam' 'spam '{:> {:< }format('spam' spam 'platform:> {[kind]:< }format(sysdict(kind='laptop')win laptop floating-point numbers support the same type codes and formatting specificity in formatting method calls as in expressions for instanc... |
802 | be used to format single item it' more concise alternative to the string format methodand is roughly similar to formatting single item with the formatting expressionstring method '{ }format( ' format( '' ' ' built-in function expression technicallythe format built-in runs the subject object' __format__ methodwhich the ... |
803 | 'first=%slast=%smiddle=%sparts "first=slast=mmiddle=[' '' ']when more complex formatting is applied the two techniques approach parity in terms of complexityalthough if you compare the following with the format method call equivalents listed earlier you'll again find that the expressions tend to be bit simpler and more... |
804 | data dict(platform=sys platformkind='laptop''my {kind: }format(**data'my laptop runs win 'my %(kind)- runs %(platform) sdata 'my laptop runs win as we'll see in the **data in the method call here is special syntax that unpacks dictionary of keys and values into individual "name=valuekeyword arguments so they can be ref... |
805 | '%smoney( '$ , and as usuala simple function like this can be applied in more advanced contexts toosuch as the iteration tools we met in and will study fully in later [commas(xfor in ( )[' , , '' , , ''% %stuple(commas(xfor in ( )' , , , , 'join(commas(xfor in ( )' , , , , for better or worsepython developers often see... |
806 | case for binary formatting'{ : }format(( * expression (onlybinary format code ' '% (( * valueerrorunsupported format character 'bbin(( * ' '%sbin(( * ' '{}format(bin(( * )' but other more general options work too '%sbin(( * )[ :' slice off to get exact equivalent usable with both method and expression with relative num... |
807 | can reference the same value multiple times'{name{job{name}format(name='bob'job='dev''bob dev bob'%(name) %(job) %(name)sdict(name='bob'job='dev''bob dev bobespecially in common practicethoughthe expression seems just as simpleor simplerd dict(name='bob'job='dev''{ [name]{ [job]{ [name]}format( 'bob dev bob'{name{job{n... |
808 | less cluttered'{ : }{ }{ : }format( ' '{: }{ }{: }format( ' '% % ( ' named method and context-neutral argumentsaesthetics versus practice the formatting method also claims an advantage in replacing the operator with more mnemonic format method nameand not distinguishing between single and multiple substitution values t... |
809 | values in tuple and ignore the nontupled optionthe expression is essentially the same as the method call here moreoverthe method incurs price in inflated code size to achieve its constrained usage mode given the expression' wide use over python' historythis issue may be more theoretical than practicaland may not justif... |
810 | ' strings'{num{title}format(**dict(num= title='strings')' stringsthe module' templating system allows values to be referenced by name tooprefixed by $as either dictionary keys or keywordsbut does not support all the utilities of the other two methods-- limitation that yields simplicitythe prime motivation for this tool... |
811 | support indexing by keyetc ' including the python byte strings and unicode strings mentioned at the start of this under the general "stringslabel here (see sets are something of category unto themselves (they don' map keys to values and are not positionally ordered sequences)and we haven' yet explored mappings on our i... |
812 | in this we took an in-depth tour of the string object type we learned about coding string literalsand we explored string operationsincluding sequence expressionsstring method callsand string formatting with both expressions and method calls along the waywe studied variety of concepts in depthsuch as slicingmethod call ... |
813 | quence objectincluding stringslistsand tuples the only difference is that when you slice listyou get back new list the built-in ord(sfunction converts from one-character string to an integer character codechr(iconverts from the integer code back to string keep in mindthoughthat these integers are only ascii codes for t... |
814 | lists and dictionaries now that we've learned about numbers and stringsthis moves on to give the full story on python' list and dictionary object types--collections of other objectsand the main workhorses in almost all python scripts as you'll seeboth types are remarkably flexiblethey can be changed in placecan grow an... |
815 | nestingyou can create lists of lists of listsand so on of the category "mutable sequencein terms of our type category qualifierslists are mutable ( can be changed in placeand can respond to all the sequence operations used with stringssuch as indexingslicingand concatenation in factsequence operations work the same on ... |
816 | interpretation for in lprint(xiterationmembership in append( methodsgrowing extend([ , , ] insert(ixl index(xmethodssearching count(xl sort(methodssortingreversingl reverse(copying ( +)clearing ( + copy( clear( pop(imethodsstatementsshrinking remove(xdel [idel [ :jl[ : [ [ index assignmentslice assignment [ : [ , , [ *... |
817 | for change operations because they are mutable object type lists in action perhaps the best way to understand lists is to see them at work let' once again turn to some simple interpreter interactions to illustrate the operations in table - basic list operations because they are sequenceslists support many of the same o... |
818 | in and expanded on in their basic operation is straightforwardthough--as introduced in list comprehensions are way to build new list by applying an expression to each item in sequence (reallyin any iterable)and are close relatives to for loopsres [ for in 'spam'res ['ssss''pppp''aaaa''mmmm'list comprehensions this expr... |
819 | an item within the rowmatrix[ [ matrix[ ][ matrix[ ][ matrix [[ ][ ][ ]matrix[ ][ notice in the preceding interaction that lists can naturally span multiple lines if you want them to because they are contained by pair of bracketsthe " here are python' continuation line prompt (see for comparable code without the "sand ... |
820 | directlyrather than generating new list object for the result index assignment in python works much as it does in and most other languagespython replaces the single object reference at the designated offset with new one slice assignmentthe last operation in the preceding examplereplaces an entire section of list in sin... |
821 | front of the list--per the next section' method coveragesomething the list' extend does more mnemonically at list endl [ [: [ insert all at : an empty slice at front [ [len( ):[ insert all at len( ):an empty slice at end [ extend([ ]insert all at endnamed method [ list method calls like stringspython list objects also ... |
822 | arguments-- special "name=valuesyntax in function calls that specifies passing by name and is often used for giving configuration options in sortsthe reverse argument allows sorts to be made in descending instead of ascending orderand the key argument gives one-argument function that returns the value to be used in sor... |
823 | placebut don' return the list as result (technicallythey both return value called noneif you say something like = append( )you won' get the modified value of (in factyou'll lose the reference to the list altogether!when you use attributes such as append and sortobjects are changed as side effectso there' no reason to r... |
824 | [ append( append( [ pop( [ push onto stack pop off stack the pop method also accepts an optional offset of the item to be deleted and returned (the default is the last item at offset - other list methods remove an item by value (remove)insert an item at an offset (insert)count the number of occurrences (count)and searc... |
825 | indexon the other handjust stores reference to the empty list object in the specified slotrather than deleting an iteml ['already''got''one' [ :[ ['already' [ [ [[]although all the operations just discussed are typicalthere may be additional list methods and operations not illustrated here the method setfor examplemay ... |
826 | unlike in listitems stored in dictionary aren' kept in any particular orderin factpython pseudo-randomizes their left-to-right order to provide quick lookup keys provide the symbolic (not physicallocations of items in dictionary variable-lengthheterogeneousand arbitrarily nestable like listsdictionaries can grow and sh... |
827 | operation interpretation {empty dictionary {'name''bob''age' two-item dictionary {'cto'{'name''bob''age' }nesting dict(name='bob'age= alternative construction techniquesd dict([('name''bob')('age' )]keywordskey/value pairszipped key/value pairskey lists dict(zip(keyslistvalueslist) dict fromkeys(['name''age'] ['name'in... |
828 | to the interpreter to get feel for some of the dictionary operations in table - basic dictionary operations in normal operationyou create dictionaries with literals and store and access items by key with indexingpython {'spam' 'ham' 'eggs' ['spam' {'eggs' 'spam' 'ham' make dictionary fetch value by key order is "scramb... |
829 | iterators more formally in and also note the syntax of the last example in this listing we have to enclose it in list call in python for similar reasons--keys in returns an iterable objectinstead of physical list the list call forces it to produce all its values at once so we can print them interactivelythough this cal... |
830 | them in list call there to collect their values all at once for displayd {'spam' 'ham' 'eggs' list( values()[ list( items()[('eggs' )('spam' )('ham' )in realistic programs that gather data as they runyou often won' be able to predict what will be in dictionary before the program is launchedmuch less when it' coded fetc... |
831 | ['aa''bb''cc' pop( 'bbl ['aa''cc'delete from specific position dictionaries also provide copy methodwe'll revisit this in as it' way to avoid the potential side effects of shared references to the same dictionary in factdictionaries come with more methods than those listed in table - see the python library manualdir an... |
832 | print(year '\ttable[year] life of brian holy grail the meaning of life same asfor year in table keys(the last command uses for loopwhich we previewed in but haven' covered in detail yet if you aren' familiar with for loopsthis command simply iterates through each key in the table and prints tab-separated list of keys a... |
833 | multiple ways to map values back to keys with bit of extra generalizable codek 'holy grailtable[ ' key=>value (normal usagev ' [key for (keyvaluein table items(if value = ['holy grail'[key for key in table keys(if table[key= ['holy grail'value=>key ditto note that both of the last two commands return list of titlesin d... |
834 | the last point in the prior list is important enough to demonstrate with few examples when you use listsit is illegal to assign to an offset that is off the end of the listl [ [ 'spamtraceback (most recent call last)file ""line in indexerrorlist assignment index out of range although you can use repetition to prealloca... |
835 | matrix {( ) ( ) herewe've used dictionary to represent three-dimensional array that is empty except for the two positions ( , , and ( , , the keys are tuples that record the coordinates of nonempty slots rather than allocating large and mostly empty threedimensional matrix to hold these valueswe can use simple two-item... |
836 | the same role as "recordsor "structsin other languages the followingfor examplefills out dictionary describing hypothetical personby assigning to new keys over time (if you are bobmy apologies for picking on your name in this book--it' easy to type!)rec {rec['name''bobrec['age' rec['job''developer/managerprint(rec['nam... |
837 | db['bob']['jobs'later in the book we'll meet tools such as python' shelvewhich works much the same waybut automatically maps objects to and from files to make them permanent (watch for more in this sidebar "why you will caredictionary interfaceson page other ways to make dictionaries finallynote that because dictionari... |
838 | python careeryou'll probably find uses for all of these dictionary-creation forms as you start applying them in realisticflexibleand dynamic python programs the listings in this section document the various ways to create dictionaries in both python and howeverthere is yet another way to create dictionariesavailable on... |
839 | much like the keys of valueless dictionarythey don' map keys to valuesbut can often be used like dictionaries for fast lookups when there is no associated valueespecially in search routinesd { ['state 'true 'state in true set( add('state ''state in true visited-state dictionary samebut with sets watch for rehash of thi... |
840 | but is presented here in the context of extensions because of its origin with that in mindlet' take look at what' new in dictionaries in and dictionary comprehensions in and as mentioned at the end of the prior sectiondictionaries in and can also be created with dictionary comprehensions like the set comprehensions we ... |
841 | {'eggs''eggs!''spam''spam!''ham''ham!'dictionary comprehensions are also useful for initializing dictionaries from keys listsin much the same way as the fromkeys method we met at the end of the preceding sectiond dict fromkeys([' '' '' '] {' ' ' ' ' ' initialize dict from keys { : for in [' '' '' '] {' ' ' ' ' ' samebu... |
842 | here it' enough to know that we have to run the results of these three methods through the list built-in if we want to apply list operations or display their values for examplein python (other version' outputs may differ slightly) dict( = = = {' ' ' ' ' ' keys( dict_keys([' '' '' ']list( [' '' '' 'makes view object in ... |
843 | {' ' ' ' ' ' keys( values(list( [' '' '' 'list( [ views maintain same order as dictionary del [' ' {' ' ' ' change the dictionary in place list( [' '' 'list( [ reflected in any current view objects not true in xlists detached from dict dictionary views and sets also unlike ' list results ' view objects returned by the ... |
844 | {' '' '' '' 'union keys and set items views are set-like too if they are hashable--that isif they contain only immutable objectsd {' ' list( items()[(' ' ) items( keys({(' ' )' ' items( {(' ' )' 'items set-like if hashable union view and view dict treated same as its keys items({(' ' )(' ' ){(' ' )(' ' )(' ' )set of ke... |
845 | of theseusing the dictionary' keys iterator is probably preferable in xand works in as welld {' ' ' ' ' ' for in sorted( )print(kd[ ] better yetsort the dict directly dict iterators return keys dictionary magnitude comparisons no longer work in secondlywhile in python dictionaries may be compared for relative magnitude... |
846 | and care about compatibility (or suspect that you might someday)here are some pointers of the changes we've met in this sectionthe first (dictionary comprehensionscan be coded only in and the second (dictionary viewscan be coded only in xand with special method names in howeverthe last three techniques--sortedmanual co... |
847 | type is similarbut it stores items by key instead of by position and does not maintain any reliable left-to-right order among its items both lists and dictionaries are mutableand so support variety of in-place change operations not available for stringsfor examplelists can be grown by append callsand dictionaries by as... |
848 | placeand pop(keyremoves key and returns the value it had dictionaries also have othermore exotic in-place change methods not presented in this such as setdefaultsee reference sources for more details dictionaries are generally better when the data is labeled ( record with field namesfor example)lists are best suited to... |
849 | tuplesfilesand everything else this rounds out our in-depth tour of the core object types in python by exploring the tuplea collection of other objects that cannot be changedand the filean interface to external files on your computer as you'll seethe tuple is relatively simple object that largely performs operations yo... |
850 | the file coverage here will apply both to typical text and binary files of the sort we'll meet hereas well as to more advanced file-processing modes you may choose to explore later tuples the last collection type in our survey is the python tuple tuples construct simple groups of objects they work exactly like listsexc... |
851 | interpretation ('bob'('dev''mgr')nested tuples tuple('spam'tuple of items in an iterable [iindexindex of indexslicelength [ ][jt[ :jlen(tconcatenaterepeat iterationmembership for in tprint( 'spamin [ * for in tmethods in and xsearchcount index('ni' count('ni'namedtuple('emp'['name''jobs']named tuple extension type tupl... |
852 | ( , tuple containing an integer as special casepython also allows you to omit the opening and closing parentheses for tuple in contexts where it isn' syntactically ambiguous to do so for instancethe fourth line of table - simply lists four items separated by commas in the context of an assignment statementpython recogn... |
853 | then back to tuplereallyboth calls make new objectsbut the net effect is like conversion list comprehensions can also be used to convert tuples the followingfor examplemakes list from tupleadding to each item along the wayt ( [ for in tl [ list comprehensions are really sequence operations--they always build new listsb... |
854 | tuple as simple association of objects and list as data structure that changes over time in factthis use of the word "tuplederives from mathematicsas does its frequent use for row in relational database table the best answerhoweverseems to be that the immutability of tuples provides some integrity--you can be sure tupl... |
855 | values to tuple (['dev''mgr']'bob' list(bob items()items to tuple list [('jobs'['dev''mgr'])('name''bob')('age' )but with bit of extra workwe can implement objects that offer both positional and named access to record fields for examplethe namedtuple utilityavailable in the standard library' collections module mentione... |
856 | named tuples accept these by namepositionor both)bob rec('bob' ['dev''mgr']nameagejobs bob namejobs ('bob'['dev''mgr']for both tuples and named tuples tuple assignment (for in bobprint(xprints bob ['dev''mgr'iteration context tuple-unpacking assignment doesn' quite apply to dictionariesshort of fetching and converting ... |
857 | operation interpretation output open( ' :\spam'' 'create output file ('wmeans writeinput open('data'' 'create input file ('rmeans readinput open('data'same as prior line ('ris the defaultastring input read(read entire file into single string astring input read(nread up to next characters (or bytesinto string astring in... |
858 | unicode encodings are turned offadding opens the file for both input and output ( you can both read and write to the same file objectoften in conjunction with seek operations to reposition in the fileboth of the first two arguments to open must be python strings an optional third argument can be used to control output ... |
859 | by defaultoutput files are always bufferedwhich means that text you write may not be transferred from memory to disk immediately--closing fileor running its flush methodforces the buffered data to disk you can avoid buffering with extra open argumentsbut it may impede performance python files are also randomaccess on b... |
860 | myfile close(myfile open('myfile txt'myfile readline('hello text file\nmyfile readline('goodbye text file\nmyfile readline('flush output buffers to disk open for text input'ris default read the lines back empty stringend-of-file notice that file write calls return the number of characters written in python xin they don... |
861 | '#/usr/bin/env python \nthe raw string form in the second command is still useful to turn off accidental escapes when you can' control string contentand in other contexts text and binary filesthe short story strictly speakingthe example in the prior section uses text files in both python and xfile type is determined by... |
862 | ' python / bin(function in additionbinary files do not perform any end-of-line translation on datatext files by default map all forms to and from \ when written and read and implement unicode encodings on transfers in binary files like this one work the same in python xbut byte strings are simply normal strings and hav... |
863 | like indexingadditionand so onf open('datafile txt'line readline(line 'spam\nline rstrip('spamopen again read one line remove end-of-line for this first linewe used the string rstrip method to get rid of the trailing end-of-line charactera line[:- slice would worktoobut only if we can be sure all lines end in the \ cha... |
864 | [[ ]{' ' ' ' }because the end result of all this parsing and converting is list of normal python objects instead of stringswe can now apply list and dictionary operations to them in our script storing native python objectspickle using eval to convert from strings to objectsas demonstrated in the preceding codeis powerf... |
865 | modebinary mode is always required in python xbecause the pickler creates and uses bytes string objectand these objects imply binarymode files (text-mode files imply str strings in xin earlier pythons it' ok to use text-mode files for protocol (the defaultwhich creates ascii text)as long as text mode is used consistent... |
866 | '{"job"["dev""mgr"]"name"{"last""smith""first""bob"}"age" } json loads(so {'job'['dev''mgr']'name'{'last''smith''first''bob'}'age' =rec true it' similarly straightforward to translate python objects to and from json data strings in files prior to being stored in fileyour data is simply python objectsthe json module rec... |
867 | [' ''bbb''cc''dddd'[' '' '' '' 'storing packed binary datastruct one other file-related note before we move onsome advanced applications also need to deal with packed binary datacreated perhaps by language program or network connection python' standard library includes tool to help in this domain--the struct module kno... |
868 | you'll also want to watch for ' discussion of the file' context manager supportnew as of python and though more feature of exception processing than files themselvesit allows us to wrap file-processing code in logic layer that ensures that the file will be closed (and if neededhave its output flushed to diskautomatical... |
869 | preopened file objects in the sys modulesuch as sys stdout (see "print operationson page in for detailsdescriptor files in the os module integer file handles that support lower-level tools such as file locking (see also the "xmode in python ' open for exclusive creationsocketspipesand fifos file-like objects used to sy... |
870 | --stringslistsand tuples--all share sequence operations such as concatenationlengthand indexing only mutable objects--listsdictionariesand sets--may be changed in placeyou cannot change numbersstringsor tuples in place files export only methodsso mutability doesn' really apply to them--their state may be changed when t... |
871 | preferred in iterations and so on we can also make the new object mutable or not by selectively implementing methods called for in-place change operations ( __setitem__ is called on self[index]=value assignmentsalthough it' beyond this book' scopeit' also possible to implement new objects in an external language like a... |
872 | expression ['abc'[( )([ ] )] syntactically nested objects are internally represented as references ( pointersto separate pieces of memory changing mutable object in place may affect other references to the same object elsewhere in your program if you don' want such behavioryou'll need to tell python to copy the object ... |
873 | within the objects referenced by and dchanging the shared list from makes it look different from and dtoo store the same reference in more than one place (variableslistsand so onthis is feature--you can pass large object around program without generating expensive copies of it along the way if you really do want copies... |
874 | ([ 'ni' ]{' ' ' ''spam'' ' }in terms of our original exampleyou can avoid the reference side effects by slicing the original list instead of simply naming itx [ [' ' [:]' ' {' ': [:]' ': embed copies of ' object this changes the picture in figure - -- and will now point to different lists than the net effect is that ch... |
875 | (truefalseequivalentsame objectherel and are assigned lists that are equivalent but distinct objects as review of what we saw in because of the nature of python referencesthere are two ways to test for equalitythe =operator tests value equivalence python performs an equivalence testcomparing all nested objects recursiv... |
876 | numbers are compared by relative magnitudeafter conversion to the common highest type if needed strings are compared lexicographically (by the character set code point values returned by ord)and character by character until the end or first mismatch ("abc"ac"lists and tuples are compared by comparing each component fro... |
877 | ditto for sorts [ ' 'sort(typeerrorunorderable typesstr(int( true str( >' ' >int(' '(truetruemixed numbers convert to highest type manual conversions force the issue python and dictionary comparisons the second-to-last point in the preceding section also merits illustration in python xdictionaries support magnitude com... |
878 | notice that the test results returned in the last two examples represent true and false values they print as the words true and falsebut now that we're using logical tests like these in earnesti should be bit more formal about what these names really mean in pythonas in most programming languagesan integer represents f... |
879 | fill it with none objectsl [none [nonenonenonenonenonenonenonethis doesn' limit the size of the list (it can still grow and shrink later)but simply presets an initial size to allow for future index assignments you could initialize list with zeros the same wayof coursebut best practice dictates using none if the type of... |
880 | as summary and referencefigure - sketches all the built-in object types available in python and their relationships we've looked at the most prominent of thesemost of the other kinds of objects in figure - correspond to program units ( functions and modulesor exposed interpreter internals ( stack frames and compiled co... |
881 | in pythoneven the type of an objectsome extension typessuch as named tuplesmight belong in this figure toobut the criteria for inclusion in the core types set are not formal core types review and summary |
882 | general apply to instances of user-defined classes in shortin python and for new-style classes in python xthe type of class instance is the class from which the instance was made for classic classes in python xall class instances are instead of the type "instance,and we must compare instance __class__ attributes to com... |
883 | [' '[ ]' 'changes too this effect usually becomes important only in larger programsand shared references are often exactly what you want if objects change out from under you in unwanted waysyou can avoid sharing objects by copying them explicitly for listsyou can always make top-level copy by using an empty-limits slic... |
884 | [list( ) embed (sharedcopy of [ [[ ][ ][ ][ ]even more subtlyalthough doesn' share an object with anymoreit still embeds four references to the same copy of it if you must avoid that sharing tooyou'll want to make sure each embedded copy is uniquey[ ][ all four copies are still the same [[ ][ ][ ][ ] [ [list(lfor in ra... |
885 | reference themselves may be more surprise than asset immutable types can' be changed in place and once more for completenessyou can' change an immutable object in place insteadyou construct new object with slicingconcatenationand so onand assign it back to the original referenceif neededt ( [ errort [: ( ,ok( that migh... |
886 | write an expression that changes the first item in tuple ( should become ( in the process what is the default for the processing mode argument in file open call what module might you use to store python objects in file without converting them to strings yourself how might you go about copying all parts of nested struct... |
887 | this session asks you to get your feet wet with built-in object fundamentals as beforea few new ideas may pop up along the wayso be sure to flip to the answers in appendix when you're done (or even when you're notif you have limited timei suggest starting with exercises and (the most practical of the bunch)and then wor... |
888 | four strings or numbers ( =[ , , , ]thenexperiment with the following boundary cases you may never see these cases in real programs (especially not in the bizarre ways they appear here!)but they are intended to make you think about the underlying modeland some may be useful in less artificial forms--slicing out of boun... |
889 | ( string listlist tuple) does work when one of the operands is dictionaryc does the append method work for both lists and stringshow about using the keys method on lists(hintwhat does append assume about its subject object? finallywhat type of object do you get back when you slice or concatenate two lists or two string... |
890 | statements and syntax |
891 | introducing python statements now that you're familiar with python' core built-in object typesthis begins our exploration of its fundamental statement forms as in the previous partwe'll begin here with general introduction to statement syntaxand we'll follow up with more details about specific statements in the next fe... |
892 | table - summarizes python' statement set each statement in python has its own specific purpose and its own specific syntax--the rules that define its structure-thoughas we'll seemany share common syntax patternsand some statementsroles overlap table - also gives examples of each statementwhen coded according to its syn... |
893 | role example def function()nonlocal xx 'newimport module access import sys from attribute access from sys import stdin class building objects class subclass(superclass)staticdata [def method(self)pass try/exceptfinally catching exceptions tryraise triggering exceptions raise endsearch(locationassert debugging checks as... |
894 | try statement in with/as is an optional extensionand it is not available unless you explicitly turn it on by running the statement from __future__ import with_statement (see tale of two ifs before we delve into the details of any of the concrete statements in table - want to begin our look at python statement syntax by... |
895 | certainly forget the colon character very soon you'll get an error message if you doand most python-friendly editors make this mistake easy to spot including it eventually becomes an unconscious habit (so much so that you may start typing colons in your -like language codetoogenerating many entertaining error messages ... |
896 | required heretooif you are pining for your programming days (if such state is possibleyou can continue to use semicolons at the end of each statement--the language lets you get away with them if they are presentbecause the semicolon is also separator when statements are combined but don' do that either (really!againdoi... |
897 | readable (unlike much of the code written in -like languagesto put that more stronglyaligning your code according to its logical structure is major part of making it readableand thus reusable and maintainableby yourself and others in facteven if you never use python after reading this bookyou should get into the habit ... |
898 | makes this "block-structured code(he sayssarcasticallynoin any block-structured languagepython or otherwiseif nested blocks are not indented consistentlythey become very difficult for the reader to interpretchangeor reusebecause the code no longer visually reflects its logical meaning readability mattersand indentation... |
899 | key backs up one level of indentationand you can customize how far to the right idle indents statements in nested block there is no universal standard on thisfour spaces or one tab per level is commonbut it' generally up to you to decide how and how much you wish to indent (unless you work at company that' endured poli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.